C# 为什么要创建自定义异常?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/417428/
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
Why Create Custom Exceptions?
提问by Yoann. B
Why do we need to create custom exceptions in .NET?
为什么我们需要在 .NET?
采纳答案by Jon Limjap
Specific customs exceptions allow you to segregate different error types for your catch statements. The common construct for exception handling is this:
特定的海关例外允许您为 catch 语句分离不同的错误类型。异常处理的常见构造是这样的:
try
{}
catch (Exception ex)
{}
This catches allexceptions regardless of type. However, if you have custom exceptions, you can have separate handlers for each type:
无论类型如何,这都会捕获所有异常。但是,如果您有自定义异常,则可以为每种类型设置单独的处理程序:
try
{}
catch (CustomException1 ex1)
{
//handle CustomException1 type errors here
}
catch (CustomException2 ex2)
{
//handle CustomException2 type errors here
}
catch (Exception ex)
{
//handle all other types of exceptions here
}
Ergo, specific exceptions allow you a finer level of control over your exception handling. This benefit is shared not only by custom exceptions, but all other exception types in the .NET system libraries as well.
因此,特定异常允许您更好地控制异常处理。这种好处不仅由自定义异常共享,而且 .NET 系统库中的所有其他异常类型也共享。
回答by masfenix
I am not sure why "technically" but lets say I have a app/website that uses permissions. If someone does not have the right permission, its kinda stupid to throw a DivideByZero Exception or IOException. Instead I can create my AccessDeniedException which will help me debug later on.
我不确定为什么“技术上”,但可以说我有一个使用权限的应用程序/网站。如果某人没有正确的权限,抛出 DivideByZero Exception 或 IOException 有点愚蠢。相反,我可以创建我的 AccessDeniedException,这将帮助我稍后进行调试。
回答by Joel Coehoorn
So you can also throw them yourself, and then catch them and know exactlywhat they mean.
所以你也可以自己扔它们,然后抓住它们并确切地知道它们的含义。
Also: if you're building a class library/framework/api, it's often useful to create a BaseException that other exceptions in your code inherit from. Then when your code raises exceptions the programmers who are using it can quickly know the source of the exception.
另外:如果您正在构建一个类库/框架/api,创建一个 BaseException 通常很有用,您的代码中的其他异常从中继承。然后,当您的代码引发异常时,使用它的程序员可以快速知道异常的来源。
回答by krosenvold
Because it can make your intentions clear, and you can also track usages using IDE functionality. Say that you have a custom backend system called "FooBar" and you make a "FooBarDownException", you can track usages of this exception to identify any custom logic your application contains because FooBar is down. You can choose to catch this specific type of exception and ignore others, avoiding overloads and conditional logic within exception handlers. It's really just another version of strong typing. It also means you can avoid comments in your code because the exception has an intention revealing name.
因为它可以明确您的意图,并且您还可以使用 IDE 功能跟踪使用情况。假设您有一个名为“FooBar”的自定义后端系统,并且您创建了一个“FooBarDownException”,您可以跟踪此异常的使用情况以识别您的应用程序包含的任何自定义逻辑,因为 FooBar 已关闭。您可以选择捕获这种特定类型的异常并忽略其他异常,从而避免异常处理程序中的重载和条件逻辑。这实际上只是强类型的另一个版本。这也意味着您可以避免在代码中添加注释,因为该异常意图揭示 name。
回答by lc.
It's the same reason you would create different exit codes for a non-.NET application: to specify different application-specific errors. Like...ConnectionBrokenException
or um...UserSmellsBadException
...or something.
这与您为非 .NET 应用程序创建不同退出代码的原因相同:指定不同的特定于应用程序的错误。就像……ConnectionBrokenException
或者嗯…………UserSmellsBadException
什么的。
This way you can know exactly what went wrong and act appropriately. For example, if you try to send some data and the data transport class throws a ConnectionBrokenException
, you can pop up a reconnect dialog and try to reconnect. Then the reconnect method would throw a ConnectionTimeoutException
if it times out, and you can again act appropriately.
通过这种方式,您可以确切地知道出了什么问题并采取适当的行动。例如,如果您尝试发送一些数据并且数据传输类抛出一个ConnectionBrokenException
,您可以弹出一个重新连接对话框并尝试重新连接。然后,ConnectionTimeoutException
如果超时,重新连接方法将抛出 a ,您可以再次采取适当的行动。
回答by mhenry1384
The standard .NET exceptions don't cover everything bad that can go wrong in any application nor are they intended to. Unless your program is very simple, it's likely you will have to create at least a few custom exceptions.
标准的 .NET 异常并没有涵盖任何应用程序中可能出错的所有不好的东西,它们也不是故意的。除非您的程序非常简单,否则您可能必须至少创建一些自定义异常。
回答by Serge Wautier
As Joel wrote: So you can also throw them yourself, and then catch them and know exactly what they mean.
正如乔尔所写:所以你也可以自己扔它们,然后抓住它们并确切地知道它们的含义。
In addition, you can add specific info about the problem in order to let your exception handler act more accurately.
此外,您可以添加有关问题的特定信息,以便让您的异常处理程序更准确地执行操作。
回答by JaredPar
I did a lengthy blog post on this subject recently:
我最近写了一篇关于这个主题的长篇博文:
http://blogs.msdn.com/jaredpar/archive/2008/10/20/custom-exceptions-when-should-you-create-them.aspx
http://blogs.msdn.com/jaredpar/archive/2008/10/20/custom-exceptions-when-should-you-create-them.aspx
The crux of it comes down to: Only create a custom exception if one of the following are true
它的关键归结为:仅在以下情况之一为真时才创建自定义异常
- You actually expect someone to handle it.
- You want to log information about a particular error
- 你实际上希望有人来处理它。
- 您想记录有关特定错误的信息
回答by Bill K
For one thing, Exceptions are implemented in the Library, not in the language--how can they create exceptions in the library? I'm pretty sure you aren't advocating that system libraries should have a different set of rules.
一方面,异常是在库中实现的,而不是在语言中——它们如何在库中创建异常?我很确定你不是在提倡系统库应该有一套不同的规则。
For another, it's actually possible to use an object tree of exceptions. Your inherited exceptions can have special attributes if you like--they can be used for more complicated things than they are. I'm not advocating they be used as a generic data transport mechanism or anything (although they could be), but I could see a case where someone implemented a custom logging solution that required a special attribute on the Exception...
另一方面,实际上可以使用异常对象树。如果您愿意,您继承的异常可以具有特殊属性——它们可以用于比它们更复杂的事情。我不提倡将它们用作通用数据传输机制或任何东西(尽管它们可能是),但我可以看到有人实现了自定义日志记录解决方案的情况,该解决方案需要对异常进行特殊属性...
Your custom exceptions could contain a flag indicating special treatment (maybe one saying you should restart the JVM), they could contain information about logging levels, a bunch of stuff.
您的自定义异常可能包含一个指示特殊处理的标志(也许有人说您应该重新启动 JVM),它们可能包含有关日志记录级别的信息,一堆东西。
Anyway, I'm not advocating this stuff, I'm just saying it's possible. The first paragraph is you real answer.
无论如何,我不是在提倡这个东西,我只是说这是可能的。第一段是你真正的答案。
回答by ?yvind Skaar
You shouldn't if the built in Exceptions appropriately describes the problem/exception. I wouldn't make my own base classes to create a custom ArgumentException
, ArgumentNullException
or InvalidOperationException
.
如果内置的异常适当地描述了问题/异常,你不应该这样做。我不会让我自己的基类来创建自定义ArgumentException
,ArgumentNullException
或InvalidOperationException
。
You can create your own exceptions, and describe the error at a higher level. however, this usually doesn't help that much in debugging from a consumer class.
您可以创建自己的异常,并在更高级别描述错误。然而,这通常对从消费者类调试没有多大帮助。
If you throw and catch the exception yourself, a custom exception may be in order.
如果您自己抛出并捕获异常,则可能需要自定义异常。