Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try Catch or If statement?

Tags:

if you think there is a possibility of getting a null pointer exception, should you use an if statement to make sure the variable is not null, or should you just catch the exception?

I don't see any difference as you can put your logic to deal with the null pointer in the if statement, or in the catch block, so which one is best practise?

like image 734
David Klempfner Avatar asked Jun 27 '13 05:06

David Klempfner


People also ask

Is try-catch better than if?

In general, try-catch blocks are great because they will break (move to the catch statement) whenever the exception occurs. If-else blocks rely on you predicting when the error will happen. Edit: Also, catch blocks won't stop your code from halting when an error is hit.

Can we use if statement in try-catch?

Try-catch block can be used to handle system generated errors as well as to implement conditional statements by manually raising exceptions while if else block can only implement conditional statements and cannot handle system generated errors.

Can we use if in try-catch in Java?

The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

What is faster if or try?

As far as the performance is concerned, using try block for code that normally doesn't raise exceptions is faster than using if statement everytime.


2 Answers

I would say ALWAYS use logic to catch the exception, not try/catch.

Try/Catch should be used when you validate but some strange thing happens and something causes an error so you can handle it more gracefully.

like image 73
logixologist Avatar answered Sep 23 '22 15:09

logixologist


There is no single answer that will suffice here, it depends.

Let's take a few scenarios so you can see what I mean.

Scenario: Method that takes a reference type parameter that does not accept null

You're defining a method, it takes a reference type parameter, say a stream object, and you don't want to accept null as a legal input parameter.

In this case, I would say that the contract is that null is not a valid input. If some code does in fact call that method with a null reference, the contract is broken.

This is an exception, more specifically, it's an ArgumentNullException.

Example:

public void Write(Stream stream) {     if (stream == null)         throw new ArgumentNullException("stream");     ... 

I would definitely not just let the code execute until it tries to dereference the stream in this case, instead crashing with a NullReferenceException, because at that point I lost all ability to react when I know the cause.

Q. Why can't I return false instead of throwing an exception?

A. Because a return value is easy to silently ignore, do you really want your "Write" methods to just silently skip writing because you made a snafu in the calling code, passing the wrong stream object or something that cannot be written to? I wouldn't!

Scenario: Method returns a reference to an object, sometimes there is no object

In this case the contract is that null is a legal result. In my opinion, null is something to avoid because it is quite hard to make sure you handle correctly everywhere, but sometimes it is the best way.

In this case I would make sure to if my way around the result, to ensure I don't crash when the null reference comes back.

Generalisation

If you take a close look at the above two scenarios, you'll note one thing:

In both cases it comes down to what is being expected, what the contract is.

If the contract says "not null", throw an exception. Don't fall back to the old-style API way of returning false because an exceptional problem should not be silently ignored, and littering the code with if statements to ensure every method call succeeds does not make for readable code.

If the contract says "null is entirely possible", handle it with if statements.

Advertising

For getting a better grip on null problems, I would also urge you to get ReSharper for you and your team, but please note that this answer can be applied to any type of exception and error handling, the same principles applies.

With it comes attributes you can embed into your project(s) to flag these cases, and then ReSharper will highlight the code in question.

public void Write([NotNull] Stream stream)  [CanBeNull] public SomeObject GetSomeObject() 

To read more about the contract attributes that ReSharper uses, see

  • ReSharper NullReferenceException Analysis and Its Contracts
  • Contract Annotations in ReSharper 7
like image 36
Lasse V. Karlsen Avatar answered Sep 19 '22 15:09

Lasse V. Karlsen