What are some best practices for creating my own c

2020-02-24 12:13发布

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?

5条回答
Anthone
2楼-- · 2020-02-24 12:41

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

查看更多
再贱就再见
3楼-- · 2020-02-24 12:45

The base exception from where all other exceptions inherit from is System.Exception, and that is what you should inherit, unless of course you have a use for things like, say, default messages of a more specific exception.

查看更多
干净又极端
4楼-- · 2020-02-24 12:54

I think the single most important thing to remember when dealing with exceptions at any level (making custom, throwing, catching) is that exceptions are only for exceptional conditions.

查看更多
我命由我不由天
5楼-- · 2020-02-24 12:55

There is a code snippet for it. Use that. Plus, check your code analysis afterwards; the snippet leaves out one of the constructors you should implement.

查看更多
我想做一个坏孩纸
6楼-- · 2020-02-24 13:02

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.

查看更多
登录 后发表回答