web analytics

How to rethrow exceptions properly in C#?

Options

codeling 1599 - 6654
@2021-03-22 16:00:54

If you rethrow exception like the following C# code:

} catch ( Exception e ) 
{
   // do something here with e, then rethrow
   throw e;
} 

Then the stack trace information will be lost after that.

To keep the stack trace information, you have to rethrow the exception like this:

} catch ( Exception e )
{
   // do something here with e, then rethrow
   throw;
}
@2021-03-22 16:03:13

If you don't want to just rethrow the original exception, you can create a new exception with the original exception as the InnerException for reference:

} catch ( Exception e ) 
{
   // do something here with e, then rethrow
   throw new MyException("more info about the exception", ex);
} 
@2021-03-22 16:43:47

Here are some useful guidelines to guide you when you should catch exceptions.

  1. Unless you have a very good reason to catch an exception, DON'T. Exceptions are supposed to be exceptional, just like the dictionary meaning: uncommon, unusual. When in doubt, let the calling routine, or the global exception handler, deal with it. This is the golden rule.
  2. If you can correct the problem implied by the exception. For example, if you try to write to a file and it is read-only, try removing the read-only flag from the file. In this case you handled the exception and fixed the problem, so you should catch the exception and fix it.
  3. If you can provide additional information about the exception. For example, if you fail to connect via HTTP to a remote website, you can provide details about why the connection failed: was the DNS invalid? Did it time out? Was the connection closed? Did the site return 401 unauthorized, which implies that credentials are needed? In this case you want to catch the exception, and re-throw it as an inner exception with more information. This is a very good reason to catch an exception, but note that we are still re-throwing it! See above posting.
  4. Always try to catch specific exceptions. Avoid catching System.Exception whenever possible; try to catch just the specific errors that are specific to that block of code. Catch System.IO.FileNotFound instead.

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com