8
\$\begingroup\$

I have a class which throws a lot of exceptions:

    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?

\$\endgroup\$
  • \$\begingroup\$ multi-catch? might combine a few of them. \$\endgroup\$ – Thufir Oct 22 '17 at 19:09
8
\$\begingroup\$

is it ok to just catch a generic Exception and not catch each individual exception if within the catch clause of each exception im just printing the stack trace ?

Yes, it is ok to just catch a generic Exception. The result will be the same if you only print the stack trace, except that catching a generic Exception also catches unchecked (runtime)exceptions such as NullPointerExceptions.

But merely printing the stack trace is almost never ok.

| improve this answer | |
\$\endgroup\$
11
\$\begingroup\$

It is okay to just catch 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.html

In your case:

try {
    mapper.writeValue(outStream, myVal);
} catch (JsonGenerationException | JsonMappingException | IOException e) {
    e.printStackTrace();
}  
| improve this answer | |
\$\endgroup\$
4
\$\begingroup\$

By printing a stack trace, and continuing, you indicate that you can recover from the current errors. Are you sure that you will be able to recover from other errors that may be added to mapper.writeValue in future? If the answer is yes, then perhaps.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.