#856 – Choosing an Exception Type to Throw

When you throw an exception, you create and populate an instance of the System.Exception class, or one of its derived classes.

While it’s possible to throw an exception of type System.Exception, it’s not normally recommended.  You typically want to throw as specific an exception as possible, for two reasons:

  • To provide some specific details about what went wrong (e.g. filename that could not be found, rather than just a general message).
  • To allow an exception handler to catch specific types of exceptions

Typically, when throwing an exception, you do one of the following:

  • Throw an exception whose type matches one of the predefined exception types in the .NET Framework.  (E.g. System.ArgumentException)
  • Throw an instance of System.ApplicationException and provide a relevant message
  • Define your own custom exception type, which inherits from System.Exception, and throw an instance of that type.
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #856 – Choosing an Exception Type to Throw

  1. Pingback: Dew Drop – May 31, 2013 (#1,558) | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: