The parameter is an object with fields that may or may not be null. Instead going though actually figuring out how to check for null, I just wrap a try catch block around it.
This functionality isn't really essential to the application.
Is this lazy or ok in certain situations
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.
1. Errors that someone up the call chain should be handling.
2. Errors that should abort the process or application entirely. Unrecoverable errors basically.
For the first one it's important to model the exception correctly. You want to provide enough information for the someone in the call chain to properly handle it.
For the second one you just let the exception bubble all the way up. Crashing may be the only correct course of action.
In general if you are using try catch in place of `if obj == null` then you aren't really saving any effort in typing and your solution is way more expensive than the null check.