Reputation: 3381
Which of this two is better to use
if(object != null)
...
else
...
or
try{
...
} catch(NullPointerException exception){
...
}
In my school some teachers prefer the second one but I'm not sure that a good idea. Someone could tell which to use and why? Thanks in advance.
Upvotes: 0
Views: 57
Reputation: 662
Performance is not the most relevant concern here. The question is, which of the two leads to more readable/maintainable/testable programs. You can worry about performance later.
In general, don't use exceptions for flow control. They are effectively a non-local goto which makes programs more difficult to read and follow. As such, they should be reserved for exceptional situations. If you can get away with not using a try-catch block for flow control, don't. Your programs will be more readable and maintainable.
The "right" way to handle this situation is
if(object != null)
...
else
...
You can avoid the check that object is not null and not empty if there is a assertion that guarantees the return value from someMethod is not null and not empty.
It is true, however, that exceptions are locally expensive. Whether or not they will impact the performance of your program is another question altogether. But used properly, exceptions are generally not a bottleneck (who cares about performance when your application is crashing?)
Upvotes: 2
Reputation: 3995
I would check for errors. Exceptions take up more resources. However if this object is null rarely then use an exception since it shouldn't be null.
Upvotes: -1