4 ms·
What exception you catch - just NullPointerException, anything or something in between? Catching just NPE is lazy but not THAT bad. The problem is - you might
by ajuc 5y ago
What exception you catch - just NullPointerException, anything or something in between?
Catching just NPE is lazy but not THAT bad. The problem is - you might get NPE from a place you don't expect and treat it as if it happened in the place you expected.
For example is it ok to return the default result if service is null?
try {
result = service.createObjectBasingOn(param);
} catch (NullPointerException npe) {
result = createDefaultResult();
}
Maybe it is, maybe it isn't.
If you catch any exception it's even worse, because you might catch something completely unrelated, possibly some error that should cause application to crash, and you pretend you handled it and continue working on data that might have got corrupted.
> This functionality isn't really essential to the application.
But the exception you caught and pretended to handle might have been essential. Imagine you have db connection with essential unsaved data waiting for a commit and you go into this method with innovative null handling just checking if it should send optional email with confirmation to some address, and the db connection broke so you get SessionWasRolledBack exception notifying you that your data is gone. But you thought it's just some null in this optional address so you continue as if nothing happened.
- 999900000999 5y agoIt's an NPE. I added more details below, But basically this is something I expect to fail when I create new data. If this was a project at work I would find a real fix.
- ajuc 5y agoI would still find the real reason and fix it correctly. One easy trick if you already know it's throwing NPE is to debug with Exception breakpoint set to break on NPE. You will find the exact point it fails and you will know how to fix it. BTW I'm pretty frustrated when I do this to find NPE in my code only to find that spring or apache libraries throw and catch NPEs all over the place :) Don't add to the mess :)