debugjavaModerate
Catching multiple types of exceptions when writing JSON
Viewed 0 times
typesexceptionscatchingwritingmultiplewhenjson
Problem
I have a class which throws a lot of exceptions:
I think this looks messy. Is it ok to just catch a generic
try {
mapper.writeValue(outStream, myVal);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}I think this looks messy. Is it ok to just catch a generic
Exception and not catch each individual exception if within the catch clause of each exception I'm just printing the stack trace?Solution
It is okay to just catch
However rather than catching the top level
In your case:
Exception and print the stack trace.However rather than catching the top level
Exception class, you may want to look at the Java 7 exception handling: http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.htmlIn your case:
try {
mapper.writeValue(outStream, myVal);
} catch (JsonGenerationException | JsonMappingException | IOException e) {
e.printStackTrace();
}Code Snippets
try {
mapper.writeValue(outStream, myVal);
} catch (JsonGenerationException | JsonMappingException | IOException e) {
e.printStackTrace();
}Context
StackExchange Code Review Q#12767, answer score: 11
Revisions (0)
No revisions yet.