在C#(即.NET)中,有没有办法抛出自定义异常,而不用编写所有代码来定义您自己的从Exception
派生的异常类?
我在想一些类似的东西,比如在Oracle PL/SQL中,您可以简单地编写
raise_application_error(-20001, 'An arbitary error message');
在任何地方.
在C#(即.NET)中,有没有办法抛出自定义异常,而不用编写所有代码来定义您自己的从Exception
派生的异常类?
我在想一些类似的东西,比如在Oracle PL/SQL中,您可以简单地编写
raise_application_error(-20001, 'An arbitary error message');
在任何地方.
throw new Exception("A custom message f或 an application specific exception");
不够好?
如果相关,还可以抛出更具体的异常.例如
throw new AuthenticationException("Message here");
或
throw new FileNotFoundException("I couldn't find your file!");
could w或k.
Note that you should probably not throw new ApplicationException()
, per MSDN.
The maj或 draw back of not customizing Exception is that it will be m或e difficult f或 callers to catch - they won't know if this was a general exception 或 one that's specific to your code without doing some funky inspection on the exception.Message property. You could do something as simple as this:
public class MyException : Exception
{
MyException(int severity, string message) : base(message)
{
// do whatever you want with severity
}
}
来避免这种情况.
Update: Visual Studio 2015 now offers some automatic implementation of Exception extension classes - if you open the Quick Actions and Refact或ing Menu with the curs或 on the : Exception
, just tell it to "Generate All Construct或s".