HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavaModerate

Catching multiple types of exceptions when writing JSON

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
typesexceptionscatchingwritingmultiplewhenjson

Problem

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?

Solution

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();
}

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.