Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some best practices for creating my own custom exception?

Tags:

In a follow-up to a previous question regarding exceptions, what are best practices for creating a custom exception in .NET?

More specifically should you inherit from System.Exception, System.ApplicationException or some other base exception?

like image 683
mattruma Avatar asked Sep 10 '08 17:09

mattruma


2 Answers

In the C# IDE, type 'exception' and hit TAB. This will expand to get you started in writing a new exception type. There are comments withs links to some discussion of exception practices.

Personally, I'm a big fan of creating lots of small classes, at that extends to exception types. For example, in writing the Foo class, I can choose between:

  1. throw new Exception("Bar happened in Foo");
  2. throw new FooException("Bar happened");
  3. throw new FooBarException();

where

class FooException : Exception  {     public FooException(string message) ...  } 

and

class FooBarException : FooException  {     public FooBarException()          : base ("Bar happened")      {     } } 

I prefer the 3rd option, because I see it as being an OO solution.

like image 123
Jay Bazuzi Avatar answered Jan 01 '23 21:01

Jay Bazuzi


Inherit from System.Exception. System.ApplicationException is useless and the design guidelines say "Do not throw or derive from System.ApplicationException."

See http://blogs.msdn.com/kcwalina/archive/2006/06/23/644822.aspx

like image 38
Mark Cidade Avatar answered Jan 01 '23 20:01

Mark Cidade