C# 有没有办法在没有 Exception 类的情况下抛出自定义异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29994402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to throw custom exception without Exception class
提问by Wernfried Domscheit
Is there any way in C# (i.e. in .NET) to throw a custom exception but without writing all the code to define your own exception class derived from Exception?
在 C#(即在 .NET 中)中是否有任何方法可以抛出自定义异常,但无需编写所有代码来定义您自己的异常类派生自Exception?
I am thinking something similar you have for example in Oracle PL/SQL where you can simply write
我在想一些类似的东西,例如在 Oracle PL/SQL 中,您可以简单地编写
raise_application_error(-20001, 'An arbitary error message');
at any place.
在任何地方。
采纳答案by Dan Field
throw new Exception("A custom message for an application specific exception");
Not good enough?
还不够好?
You could also throw a more specific exception if it's relevant. For example,
如果相关,您还可以抛出更具体的异常。例如,
throw new AuthenticationException("Message here");
or
或者
throw new FileNotFoundException("I couldn't find your file!");
could work.
可以工作。
Note that you should probably notthrow new ApplicationException(), per MSDN.
请注意,根据MSDN,您可能不应该这样做。 throw new ApplicationException()
The major draw back of not customizing Exception is that it will be more difficult for callers to catch - they won't know if this was a general exception or 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:
不自定义 Exception 的主要缺点是调用者更难捕获 - 他们不会知道这是一个一般异常还是特定于您的代码的异常,而无需对 exception.Message 属性进行一些时髦的检查。你可以做一些像这样简单的事情:
public class MyException : Exception
{
MyException(int severity, string message) : base(message)
{
// do whatever you want with severity
}
}
to avoid that.
为了避免这种情况。
Update: Visual Studio 2015 now offers some automatic implementation of Exception extension classes - if you open the Quick Actions and Refactoring Menuwith the cursor on the : Exception, just tell it to "Generate All Constructors".
更新:Visual Studio 2015 现在提供了一些异常扩展类的自动实现 - 如果您打开Quick Actions and Refactoring Menu并将光标放在 上: Exception,只需告诉它“生成所有构造函数”。
回答by Alex
You can just throw one of the exceptions that is available in .NET:
您可以只抛出 .NET 中可用的异常之一:
throw new System.ArgumentException("Parameter cannot be null", "original");
Or more generic:
或更通用:
throw new ApplicationException("File storage capacity exceeded.");
回答by Fenton
Short answer - no.
简短的回答 - 不。
There is a good reason for enforcing the inheritance of custom exceptions; people need to be able to handle them. If you could throw your custom exception without having a type, people wouldn't be able to catch that exception type.
强制继承自定义异常是有充分理由的;人们需要能够处理它们。如果您可以在没有类型的情况下抛出自定义异常,那么人们将无法捕获该异常类型。
If you don't want to write a custom exception, use an existing exception type.
如果您不想编写自定义异常,请使用现有的异常类型。
回答by David
The Exceptionclass is not an abstract, and like most of the exceptions defined in .NET, takes a string messagein one of the constructor overloads - you can therefore use an existing exception type, but with a customized message.
该Exception班是不是abstract,像大多数在.NET中定义的异常,需要string message在构造函数重载之一-因此,你可以使用现有的异常类型,但有一个自定义的消息。
throw new Exception("Something has gone haywire!");
throw new ObjectDisposedException("He's Dead, Jim");
throw new InvalidCastException(
$"Damnit Jim I'm a {a.GetType().Name}, not a {b.GetType().Name}!");
Because this uses exception types that are known, it makes it easier for thrid parties to extend your libraries as well, since they don't need to look for MyArbitraryExceptionin catchstatements.
因为这使用了已知的异常类型,所以第三方也可以更轻松地扩展您的库,因为他们不需要查找MyArbitraryExceptionincatch语句。
回答by Mirko
An easy way to create custom Exceptions in c# is using a generic class. This reduces the lines of code dramatically if you need to create much exceptions (i.e. if you need to distinguish between them in your unit tests).
在 c# 中创建自定义异常的一种简单方法是使用泛型类。如果您需要创建大量异常(即,如果您需要在单元测试中区分它们),这会显着减少代码行数。
First create a simple class called CustomException<T>:
首先创建一个简单的类,名为CustomException<T>:
public class CustomException<T> : Exception where T : Exception
{
public CustomException() { }
public CustomException(string message) : base(message){ }
public CustomException(string message, Exception innerException) : base(message, innerException){ }
public CustomException(SerializationInfo info, StreamingContext context) : base(info, context){ }
}
You can override as many constructors and methods as you want (or need) to. In order to create new Exception types just add new one-liner classes:
您可以根据需要(或需要)覆盖任意数量的构造函数和方法。为了创建新的异常类型,只需添加新的单行类:
public class MyCustomException : Exception { }
public class SomeOtherException : Exception { }
If you want to raise your custom exception use:
如果要引发自定义异常,请使用:
throw new CustomException<MyCustomException>("your error description");
This keeps your Exception code simple and allows you to distinguish between those exceptions:
这使您的异常代码保持简单,并允许您区分这些异常:
try
{
// ...
}
catch(CustomException<MyCustomException> ex)
{
// handle your custom exception ...
}
catch(CustomException<SomeOtherException> ex)
{
// handle your other exception ...
}

