Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

throw new Exception vs Catch block

Tags:

c#

Is there any behavioural difference between:

if (s == null) // s is a string
{
 throw new NullReferenceException();
}

And:

try
{
  Console.Writeline(s);
}


catch (NullReferenceException Ex)
{ // logic in here 
}

Both throw exceptions of null object, if s is null. The first example is more readable as it shows exactly where the error occurs (the exception bit is right next to the line which will cause the exception).

I have seen this coding style a lot on various blogs by various coders of all sorts of skill levels, but why not just perform the main logic by checking if s is not null and thus save the exception from ever being raised? Is there a downside to this approach?

Thanks

like image 785
GurdeepS Avatar asked Sep 22 '09 22:09

GurdeepS


People also ask

Can we throw new exception in catch block?

When an exception is cached in a catch block, you can re-throw it using the throw keyword (which is used to throw the exception objects). Or, wrap it within a new exception and throw it.

What is the difference between catch and throw exception?

Try-catch block is used to handle the exception. In a try block, we write the code which may throw an exception and in catch block we write code to handle that exception. Throw keyword is used to explicitly throw an exception. Generally, throw keyword is used to throw user defined exceptions.

Is it better to use throws or try-catch?

Q #1) When to use throws throw VS try-catch in Java? Answer: The “throws” keyword is used to declare the exception with the method signature. The throw keyword is used to explicitly throw the exception. The try-catch block is used to handle the exceptions thrown by others.

What is the difference between throw and throw new exception?

throw rethrows the caught exception, retaining the stack trace, while throw new Exception loses some of the details of the caught exception. You would normally use throw by itself to log an exception without fully handling it at that point.


4 Answers

No, Console.WriteLine(null) won't throw an exception. It will just print nothing out. Now assuming you meant something like:

Console.WriteLine(s.Length);

then it makes sense... and you should use the first form. Exceptions should occur when you can't predict them ahead of time with your current information. If you can easily work out that something's wrong, it makes no sense to try an operation which is bound to fail. It leads to code which is harder to understand and performs worse.

So NullReferenceException, ArgumentNullException and the like shouldn't be caught unless they're due to a nasty API which sometimes throws exceptions which you can handle, but which shouldn't really be being thrown in the first place. This is why in Code Contracts, the default behaviour for a failed contract is to throw an exception which you can't catch explicitly, other than by catching everything (which is typically somewhere at the top of the stack).

like image 177
Jon Skeet Avatar answered Oct 05 '22 02:10

Jon Skeet


As Jon Skeet already mentioned, Console.WriteLine (null) won't throw an exception.

Next to that, I'd like to say that you should 'fail fast'. That means that you have to put 'guard' clauses in your methods, and check the arguments that have been given in your methods if they can be considered to be valid. This allows you to throw an exception yourself, and give an additional message which will be helpfull when debugging. The message can give a clear indication on what was wrong, and that is much handier then if you're faced with a NullReferenceException that has been thrown without any good information in it's message property.

like image 39
Frederik Gheysels Avatar answered Oct 05 '22 02:10

Frederik Gheysels


If you are writing a class library there may be occasions when you know that if a certain parameter contains a null value, that may cause trouble further down the line. In those cases I usually find it to be a good idea to throw an exception (even though I would probably use ArgumentNullException for that case) to make the user of the class library aware of this as early and clearly as possible.

Exceptions are not always a bad thing.

like image 44
Fredrik Mörk Avatar answered Oct 05 '22 02:10

Fredrik Mörk


Jon Skeet is right but, more generally, it's all a question of semantic.

If the situation has some applicative meaning (number out of bound, date of birth in the future, etc) you may want to test for it before doing any operation and throw a custom exception (that is one with meaning for your application).

If the situation is truly "exceptional", just write the code as if the given value were correct. See, if you put the test, you will do it everytime, knowing that the VM will do it anyway in case it needs to throw an exception. From a performance point of view, if the error happens to have a statistically small occurence, it makes no sense.

like image 24
Julian Aubourg Avatar answered Oct 05 '22 02:10

Julian Aubourg