How to handel JsonMappingException try catch [duplicate] - java

This question already has answers here:
Unable to catch JsonMappingException
(7 answers)
Closed 8 years ago.
I am new to jackson, i have written this code and my ide says at catch block .
I dont understand this . I have included jar.
incompatible types
required:java.lang.Throwable
found :org.codehaus.jackson.map.JsonMappingException
This is the method
private void jacksonTest() {
try {
org.codehaus.jackson.map.ObjectMapper mapper = new org.codehaus.jackson.map.ObjectMapper();
mapper.writeValue(new File("c:\\user.json"), someObj);
} catch (IOException ex) {
Logger.getLogger(GR_XX.class.getName()).log(Level.SEVERE, null, ex);
} catch (JsonMappingException ex) {
// incompatible types
// required:java.lang.Throwable
// found :org.codehaus.jackson.map.JsonMappingException
} catch (Exception ex) {
Logger.getLogger(GR_XX.class.getName()).log(Level.SEVERE, null, ex);
} catch (Throwable ex) {
Logger.getLogger(GR_XX.class.getName()).log(Level.SEVERE, null, ex);
}
}

As you can see in the documentation of JsonMappingException, it is a subclass of IOException. This means your first catch would already handle the JsonMappingException. If you want to handle it seperately, you'll have to catch it before IOException.

In case of Multiple catch Exception Hierarchy comes into action
Try something like this :
try {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("c:\\user.json"), someObj.class);
}
catch (JsonMappingException ex) { }
catch (IOException ex) {}
catch (Exception ex) {}
catch (Throwable ex) {}

I got answer from stackoverflow.com/a/14920842/2194456
I had the same issue. It seems the class inherited by the JsonMappingException class is not in the JAR file. I just reverted to version 1.9 which didn't have the problem.

Related

How to follow IntelliJ-IDEA's advice "catch branch identical" on try/catch block?

I'm using "ObjectInputStream" to load serialized 2D String arrays.
The problem is, My IDE, Intellij-IDEA, will throw an error unless I put a special catch condition for a ClassNotFoundException. However, when I do that it advises, "'catch' branch identical to 'IOException' branch".
I don't know what this is implying I should do.
How can I load serialized objects without getting either advice or an error?
My code:
private String[][] getPossArray(String race, boolean isFirstName) {
String[][] retVal = new String[0][];
try {
FileInputStream fis = new FileInputStream("./res/binary_files/Human_FirstNameString[][].ser");
ObjectInputStream ois = new ObjectInputStream(fis);
retVal = (String[][]) ois.readObject();
ois.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return retVal;
}
Thanks to guleryuz's comment, I found out that the advice from IntelliJ was trying to tell me that I could get rid of the advice notification by changing my catch block to catch (IOException | ClassNotFoundException e) instead of having each catch statement on it's own line.
Old Catch-Block Version:
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
New Catch-Block Version:
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}

Analyze the following code, which exception does it display? (Exception handling, java)

class Test {
public static void main(String[] args) {
try {
String s = "5.6";
Integer.parseInt(s); // Cause a NumberFormatException
int i = 0;
int y = 2 / i;
}
catch (Exception ex) {
System.out.println("NumberFormatException");
}
catch (RuntimeException ex) {
System.out.println("RuntimeException");
}
}
}
The correct answer is that the program has a compilation error. I thought that the catch (Exception ex) would catch all exceptions including NumberFormatException, that it was a general exception that caught them all?
The block:
catch (Exception ex) {
System.out.println("NumberFormatException");
}
will catch all the exceptions, as the Exception class is the base class for all the exceptions.
When you catch Exception, you catch all the exceptions that extend Exception, which, all the exceptions do. Hence it produces the error that RuntimeException has already been caught

Java JUnit - Is it possible to determine if & which exception is thrown? [duplicate]

This question already has answers here:
How to do unit test for Exceptions?
(5 answers)
Closed 8 years ago.
I've got a method in a normal class that has a try with multiple catches:
Object returnObject = null;
try {
// do some stuff to set returnObject
}
catch (NoSuchMethodException ex) {
ex.printStackTrace();
}
catch (InstantiationException ex) {
ex.printStackTrace();
}
catch (IllegalAccessException ex) {
ex.printStackTrace();
}
catch (IllegalArgumentException ex) {
ex.printStackTrace();
}
catch (InvocationTargetException ex) {
ex.printStackTrace();
}
return returnObject;
In my UnitTest I would like to test if the method successfully went through the stuff in the try, without going into one of the caught Exceptions.
I know that if I didn't had a try-catch in my normal class' method, I could just use a try-catch with Assert.fail(...);, or an ExpectedException-tag in front of the test-method.
BUT, my method does have a try-catch, and I want to UnitTest if I successfully go through the try, without going to one of the catches. (As you can see in the code above, all my catches only have a ex.printStackTrace();)
PS: I also can't use the stuff in the try to test. So I can't check if returnObject is null after the method, because in this case I want it to be null (but without going to a catch). Otherwise I wouldn't asking this question.
Thanks in advance for the responses.
I think your Unit test doesn't have to know has exception been thrown and catched within method or not. Your unit test should test contract of your method. And it shouldn't concern about how this contract is implemented. So if contract of the method is return null if something bad happened and it's OK then test it in this way. If invoker should know was exception or not while method was executing and type of exception, then you may return some wrapper-object with method hasException();
You can assign exception name in a global String variable (use global - as you already returning an object), and compare the string in assert statement. If no exception case, returned string would be blank.
public static String message=""; // global variable
Object returnObject = null;
try {
// do some stuff to set returnObject
}
catch (NoSuchMethodException ex) {
message=ex.getMessage();
ex.printStackTrace();
}
catch (InstantiationException ex) {
message=ex.getMessage();
ex.printStackTrace();
}
catch (IllegalAccessException ex) {
message=ex.getMessage();
ex.printStackTrace();
}
catch (IllegalArgumentException ex) {
message=ex.getMessage();
ex.printStackTrace();
}
catch (InvocationTargetException ex) {
message=ex.getMessage();
ex.printStackTrace();
}
return returnObject;
And assert -
assertEquals(ClassName.message.equalsIgnoreCase(""),true);
You can access the JVMs out put stream. We have done this with legacy code that unfortunately does not employ a logger, but prints all its information to System.out
For demonstration, have a look at this class that throws a given exception or none, if null is passed in the constructor. That thrown exception will be handled and printed to System.out, just like you explained in your question.
public class SystemOutClass {
private Exception exception;
public SystemOutClass(Exception exception) {
super();
this.exception = exception;
}
public Object doStuff() {
Object returnObject = null;
try {
doThrowException();
} catch (NoSuchMethodException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (InvocationTargetException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return returnObject;
}
private void doThrowException() throws NoSuchMethodException,
InstantiationException, IllegalAccessException, InvocationTargetException,
Exception {
if (exception != null) {
throw exception;
}
}
}
The according test will switch the System.out to a known ByteArrayOutputStream, which then in turn can be checked for certain contents.
public class SystemOutTest {
private PrintStream defaultOutStream;
private ByteArrayOutputStream outStream;
#Before
public void setupStandardOutStream() {
outStream = new ByteArrayOutputStream();
defaultOutStream = System.out;
System.setOut(new PrintStream(outStream));
}
#After
public void cleanUpOutStream() {
System.setOut(defaultOutStream);
}
private String getConsoleOutput() {
return outStream.toString();
}
#Test
public void handleNoSuchMethodException() {
// given
SystemOutClass handlingClass = new SystemOutClass(new NoSuchMethodException());
// when
handlingClass.doStuff();
// then
getConsoleOutput().contains("java.lang.NoSuchMethodException");
}
}
If you have a specific part of a method that you'd like to test in isolation, refactor your class accordingly:
Object doSomeStuffAndPossiblyFail()
{
Object returnObject = null;
// do some stuff to set returnObject
return returnObject;
}
Object doSomeStuffAndReportFailureAsNull()
{
Object returnObject = null;
try {
returnObject = doSomeStuffAndPossiblyFail();
}
catch (NoSuchMethodException ex) {
ex.printStackTrace();
}
catch (InstantiationException ex) {
ex.printStackTrace();
}
....
return returnObject;
}
You're now free to test that doSomeStuffAndPossiblyFail completes without throwing any exceptions.

Java reflect API wrapper (damn checked exceptions cluttering)

I have methods that look like this:
public static <U extends Entity<?, ?>> Http<List<U>> getAllFromServerThreadRun(Integer maxResults, Class<U> clazz) {
JsonObject o2 = new JsonObject(); // TODO exception chaos im projekt
// überarbeiten
o2.addProperty("maxResults", maxResults);
String s;
Type t;
try {
U o = clazz.getConstructor().newInstance();
s = (String) clazz.getDeclaredMethod("getControllerName").invoke(o);
t = (Type) clazz.getDeclaredMethod("getListType").invoke(o);
} catch (IllegalArgumentException e) {
ExceptionHandler.handle(e);
} catch (SecurityException e) {
ExceptionHandler.handle(e);
} catch (InstantiationException e) {
ExceptionHandler.handle(e);
} catch (IllegalAccessException e) {
ExceptionHandler.handle(e);
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e);
} catch (NoSuchMethodException e) {
ExceptionHandler.handle(e);
}
return new Http<List<U>>(new HttpGet(), s, "getall", t).setParams(o2).queryServer();
}
Maybe 10 of them exist in my project as of now.
I there a alternative Java reflection library that hides these exceptions for me? I don't know what to do with them, and it's just clutter.
I suggest
catch (Exception e) {
ExceptionHandler.handle(e);
}
In java 7, you can catch multiple exception types in each catch:
try {
// reflection stuff
} catch (IllegalArgumentException |
SecurityException |
InstantiationException |
etc e) {
ExceptionHandler.handle(e);
}
I sympathise with you wanting to catch (Exception e) because of the numerous types of exceptions thrown by reflection methods, but doing so carries the danger of jnintentionally catching unchecked Exceptions, like NullPointerException which may mask bugs.
If you're still in java 6 land, you're better just sucking it up I'm afraid.
As of Java 7, all reflection-related exceptions extend java.lang.ReflectiveOperationException, so you only need to catch that.
The other exceptions (IllegalArgumentException and SecurityException) are unchecked exceptions which you should not be catching at all. If either of those occurs, there's an error in your code. The proper thing to do is not to catch the exception, but to fix the code that is causing the exception.
Specifically, I can see just looking at the code that IllegalArgumentException will never occur, because it only happens if you pass an object to invoke which is not the right type, and I can see that you are passing an instance of the very class whose methods you're invoking. And SecurityException should only happen if you aren't allowed to access the methods at all.

Java Generic Exception

I am dealing with JaudioTagger API to manipulate MP3 files, I have to repeat the following exceptions over and over again... I was thinking of having a generic exception handler where I could forward each exception maybe with a flag number and the generic method would be deal with it by having different switch cases maybe ? Is it possible ? I would really appreciate if someone could give the method signature or a way to call it
} catch (CannotReadException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (ReadOnlyFileException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidAudioFrameException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (TagException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
Pre-JDK 7 all you can do is write a utility function and call it from each of the catch blocks:
private void handle(Exception ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
private void someOtherMethod() {
try {
// something that might throw
} catch (CannotReadException ex) {
handle(ex);
} catch (ReadOnlyFileException ex) {
handle(ex);
} catch (IOException ex) {
handle(ex);
} catch (InvalidAudioFrameException ex) {
handle(ex);
} catch (TagException ex) {
handle(ex);
}
}
Starting in JDK 7, you can use multi-catch:
private void someOtherMethod() {
try {
// something that might throw
} catch (CannotReadException | ReadOnlyFileException | IOException
| InvalidAudioFrameException | TagException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
See "Catching multiple exceptions".
This answer is obsolete starting with Java 7. Use multi-catch like John Watts shows in his answer.
I suggest using
try {
/* ... your code here ... */
} catch (Exception ex) {
handle(ex);
}
And handle it this way: (you have to replace the OtherException that you don't handle or remove the throws)
private static void handle(Exception ex) throws SomeOtherException {
if (ex instanceof CannotReadException || ex instanceof ReadOnlyFileException) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
} else if (ex instanceof SomeOtherException) {
throw (SomeOtherException) ex;
} else if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
} else {
throw new RuntimeException(ex);
}
}

Categories