本文介绍了.NET 中的 ApplicationException 是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了抛出异常,我通常使用内置的异常类,例如ArgumentNullExceptionNotSupportedException.但是,有时我需要使用自定义异常,在这种情况下我会写:

To throw exceptions, I usually use built-in exception classes, e.g. ArgumentNullException and NotSupportedException. However, sometimes I need to use a custom exception and in that case I write:

class SlippedOnABananaException : Exception { }
class ChokedOnAnAppleException : Exception { }

等等.然后我在我的代码中抛出并捕获这些.但是今天我遇到了 ApplicationException 类 - 我应该使用它吗?有什么用?

and so on. Then I throw and catch these in my code. But today I came across the ApplicationException class - should I be using that instead? What's it for?

拥有许多具有不同名称的有效相同的异常类似乎效率低下(我通常不需要任何单独的功能).但我不喜欢捕获通用 ApplicationException 并且不得不使用额外的代码来确定错误是什么的想法.

It does seem inefficient to have lots of effectively identical Exception classes with different names (I don't usually need any individual functionality). But I dislike the idea of catching a generic ApplicationException and having to use extra code to determine what the error was.

ApplicationException 应该在哪里适合我的代码?

Where should ApplicationException fit in with my code?

推荐答案

根据 备注:

用户应用程序,而不是公共语言运行时,会抛出从 ApplicationException 类派生的自定义异常.ApplicationException 类区分应用程序定义的异常与系统定义的异常.

如果您正在设计的应用程序需要创建自己的异常,建议您从 Exception 类派生自定义异常.最初认为自定义异常应该派生自 ApplicationException 类;然而,在实践中并没有发现这会增加显着的价值.如需了解详情,请参阅处理异常的最佳做法.

If you are designing an application that needs to create its own exceptions, you are advised to derive custom exceptions from the Exception class. It was originally thought that custom exceptions should derive from the ApplicationException class; however in practice this has not been found to add significant value. For more information, see Best Practices for Handling Exceptions.

Exception 派生它们.此外,只要有必要,我认为为您的案例创建新的例外没有问题.如果您遇到框架中已经存在异常的情况,请使用该异常,否则,请自行处理.

Derive them from Exception. Also, I don't see a problem with creating new exceptions for your cases, as long as it is warranted. If you encounter a case where there is already an exception in the framework, use that, otherwise, roll your own.

这篇关于.NET 中的 ApplicationException 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 19:07