I am trying to deal with these exception. For example when a user, loads an invalid XML file, then SAXParseException is thrown and he is asked to load another file.
it seems that "catch" won't work here.
here's my code:
public void parseXML_FROM_file (File xml_file)
{
try {
JAXBContext jc = JAXBContext.newInstance ("generated");
//Creating an Unmarshaller.
Unmarshaller u = jc.createUnmarshaller ();
//USING FILE APPROACH
System.out.println("Using FILE approach:");
JAXBElement element = (JAXBElement) u.unmarshal(xml_file);
TEST_Class mainTest = (TEST_Class) element.getValue ();
} catch (JAXBException e)
{
e.printStackTrace ();
}catch (SAXParseException e)
//do something
}catch (UnmarshalException e)
//do something
}
}
even, this wont work
catch (JAXBException,SAXParseException,UnmarshalException e)
{
//do something
}
#don robi
this is what i get:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The type JAXBException is not generic; it cannot be parameterized with arguments <SAXParseException, UnmarshalException>
Syntax error on token ",", < expected
Syntax error, insert ">" to complete ReferenceType1
at XML_Parser.parseXML_FROM_file(XML_Parser.java:64)
at Main_Class.main(Main_Class.java:13)
The exception indicates that this is a compilation exception. Once the errors are fixed in your XML_parser class you should get the JAXB behaviour you are expecting.
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The type JAXBException is not generic; it cannot be parameterized with arguments <SAXParseException, UnmarshalException>
Syntax error on token ",", < expected
Syntax error, insert ">" to complete ReferenceType1
at XML_Parser.parseXML_FROM_file(XML_Parser.java:64)
at Main_Class.main(Main_Class.java:13)
Related
I'm a beginner of AssertJ. I encountered some issue when I use AssertJ to do Unit Testing.
JAVA: version 8
AssertJ: 3.11.1
I have a source code as below, to capture an exception and throw another exception.
try {
Integer.valueOf(valueA);
} catch(Exception e) {
throw new XXXException("value is not valid", e);
}
My test case as below failed, and I was told wrong exception assert, it's a bit confusing.
Throwable thrown = catchThrowable(() -> {
contract.init(ctx, "A", "100A", "B", "200");
});
assertThat(thrown).isInstanceOf(XXXException.class);
The error message as below, it seems like the original exception was captured by AssertJ. Anyone can help? Is it a bug or my mistake of AssertJ API usage? Many Thanks.
java.lang.AssertionError:
Expecting:
<java.util.IllegalFormatConversionException: d != java.lang.String>
to be an instance of:
<xxxx.XXXException>
but was:
<"java.util.IllegalFormatConversionException: d != java.lang.String
Here's my attempt to reproduce the issue, the test passes as expected:
#Test
public void test() {
Throwable thrown = catchThrowable(() -> f());
assertThat(thrown).isInstanceOf(RuntimeException.class);
}
private void f() {
try {
Integer.valueOf("100A");
} catch (Exception e) {
throw new RuntimeException("value is not valid", e);
}
}
Can you show us what contract.init is doing?
Another possibility would be in the stack trace, if it contains a %d somewhere stack trace it might be interpreted by a String.format but hard to say without more details.
Sometimes i have an EntityFramework exception where calling SaveChanges.
I see this kind of message: "An error occurred while updating the entries. See the inner exception for details."
I have logged the stack trace, the inner exception and stuff but there is no clear explanation of the problem. I would like to see the real query (it is a mysql database), with the parameters. Do you know how i can see or log the real query ?
Thanks
You can use DbEntityValidationException handler which will let you know what was wrong precisely.
try{
//Your code here
}
catch (DbEntityValidationException ex)
{
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
var fullMessageError = string.Join("; ", errorMessages);
var exceptionMessage = string.Concat(ex.Message, "Exact Message " + fullMessageError);
}
catch (Exception ex)
{
//General Exception here
}
You can set log property of dbContext.Database and log the actual queries generated by EF.
using (var context = new MyDBContext())
{
context.Database.Log = Console.Write; // This is where you setup where to log queries
// Your code here...
}
There is a detailed documentation on MSDN https://msdn.microsoft.com/en-us/data/dn469464.aspx
"Only the types that are inherited from the Throwable class can be thrown".
Could anybody explain me. Why not every type are throwable? If in doc there no mention about function can throw exception, it's mean that it do not have exception?
For example I thought that next try-catch block would work. But it is not.
try
{
writeln("(((((((((");
latestdtonpage = dts.sort!((a,b) => a>b).front; //latest date-time. from page.
}
catch(Exception e)
{
writeln("Can't select the latest Date from parsed date");
writeln(e);
}
But output in case of exception is next (no exception text):
(((((((((
core.exception.AssertError#C:\D\dmd2\windows\bin\..\..\src\phobos\std\array.d(73
9): Attempting to fetch the front of an empty array of DateTime
----------------
0x0051C4C9 in _d_assert_msg
0x00468E78 in pure nothrow ref #property #nogc #safe std.datetime.DateTime std.r
ange.__T11SortedRangeTAS3std8datetime8DateTimeS473app19StackOverflowParser5parse
MFAyaZ9__lambda2Z.SortedRange.front() at C:\D\dmd2\windows\bin\..\..\src\phobos\
std\range.d(8418)
0x0044F908 in void app.StackOverflowParser.parse(immutable(char)[]) at D:\code\T
rendoMetr\source\app.d(173)
0x0044F700 in app.StackOverflowParser app.StackOverflowParser.__ctor(app.DBConne
ct) at D:\code\TrendoMetr\source\app.d(150)
0x0044F199 in _Dmain at D:\code\TrendoMetr\source\app.d(33)
0x0052EDCA in D2rt6dmain211_d_run_mainUiPPaPUAAaZiZ6runAllMFZ9__lambda1MFZv
0x0052ED9F in void rt.dmain2._d_run_main(int, char**, extern (C) int function(ch
ar[][])*).runAll()
0x0052ECB5 in _d_run_main
0x00470198 in main
0x005667D1 in mainCRTStartup
0x76D1336A in BaseThreadInitThunk
0x772A9F72 in RtlInitializeExceptionChain
0x772A9F45 in RtlInitializeExceptionChain
Error executing command run: Program exited with code 1
How I can throw exception in this code?
Your code throws an AssertError, indicating that dts.sort!((a,b) => a>b) is empty, and you shouldn't call .front on it. Instead, query .empty first, and act accordingly when it's true.
AssertError inherits from Error which in turn inherits from Throwable but not from Exception. So catch(Exception e) doesn't catch it. And you should not catch Errors anyway, as they indicate that the program is in an unrecoverable error-state.
AssertError in particular signals a logic bug in your program. Here: calling .front on an empty range. Don't catch AssertError, but fix your code instead.
I'm using the Newtonsoft json.NET parser for JSON parsing. In my deserialization, I have the following code so that errors when converting from String to Int will not force me to throw away the entire object:
var param2 = new JsonSerializerSettings
{
Error = delegate(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
{
args.ErrorContext.Handled = true;
}
};
bcontent = JsonConvert.DeserializeObject<BContent>(json, param2);
I do not have control of the input data and the parsing errors are very common so I need to be versatile enough to handle them. Unfortunately, marking all errors as handled causes the deserialization to not terminate when it runs into a different error in a constrained environment.
What I want to do is to mark the errors as handled when they are of a type with a similar message as:
Could not convert string to integer....
But not when they are something different, such as this error which causes the hang:
Unterminated string. Expected delimiter...
What I can do is something like this:
Error = delegate(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
{
if (args.ErrorContext.Error.Message.Contains("convert string to integer"))
args.ErrorContext.Handled = true;
}
But it seems like there's no other way to determine a more specific error than JsonReaderException. Has anyone encountered this issue before and found a better workaround than a String.Contains()?
I'm using ScalaTest for testing some Scala code.
I currently testing for expected exceptions with code like this
import org.scalatest._
import org.scalatest.matchers.ShouldMatchers
class ImageComparisonTest extends FeatureSpec with ShouldMatchers{
feature("A test can throw an exception") {
scenario("when an exception is throw this is expected"){
evaluating { throw new Exception("message") } should produce [Exception]
}
}
}
But I would like to add additional check on the exception, e.g. I would like to check that the exceptions message contains a certain String.
Is there a 'clean' way to do this? Or do I have to use a try catch block?
I found a solution
val exception = intercept[SomeException]{ ... code that throws SomeException ... }
// you can add more assertions based on exception here
You can do the same sort of thing with the evaluating ... should produce syntax, because like intercept, it returns the caught exception:
val exception =
evaluating { throw new Exception("message") } should produce [Exception]
Then inspect the exception.
If you need to further inspect an expected exception, you can capture it using this syntax:
val thrown = the [SomeException] thrownBy { /* Code that throws SomeException */ }
This expression returns the caught exception so that you can inspect it further:
thrown.getMessage should equal ("Some message")
you can also capture and inspect an expected exception in one statement, like this:
the [SomeException] thrownBy {
// Code that throws SomeException
} should have message "Some message"