.NET抛出自定义异常 [英] .NET Throwing Custom Exceptions

查看:112
本文介绍了.NET抛出自定义异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以揭示抛出自定义异常(它从System.Exception继承),或使用它们的正确方法的利弊一些轻?我已经意识到的时候/时不要乱扔异常,但是我正在寻找如何创建自己的自定义异常的指导。

Can anyone shed some light on the pros and cons of throwing custom exceptions (which inherit from System.Exception), or the proper way to use them? I'm already aware of the when/when not to throw exception, but I am looking for guidance on how to create my own custom exceptions.

推荐答案

这些都是伟大的职位。到目前为止,我最认同与布赖恩·拉斯穆森 - 当你要处理不同类型的特殊例外创建自定义异常。

These are all great posts. So far I agree most with Brian Rasmussen -- create custom exceptions when you want to handle different types of specific exceptions.

也许一个例子帮助。这是一个人为的例子,并且可以是或可以不是在日常code有用。假设你有负责验证用户的类。这个类中,除了验证用户,有一个锁定机构,以几个失败的尝试之后锁定用户。在这种情况下,你可能会设计为类两个自定义异常的一部分: AuthenticationFailedException UserLockedOutException 。那么你的 authenticateUser的方法会简单地返回,没有抛出,如果用户成功通过身份验证,抛出 AuthenticationFailedException 如果用户认证失败,或者抛出 UserLockedOutException 如果用户被锁定。

Perhaps an example will help. This is a contrived example, and may or may not be useful in everyday code. Suppose you have a class responsible for authenticating a user. This class, in addition to authenticating a user, has a lock-out mechanism to lock out a user after several failed attempts. In such a case, you might design as part of the class two custom exceptions: AuthenticationFailedException and UserLockedOutException. Your AuthenticateUser method would then simply return without throwing if the user was successfully authenticated, throw AuthenticationFailedException if the user failed authentication, or throw UserLockedOutException if the user was locked out.

例如:

try
{
    myAuthProvider.AuthenticateUser(username, password);
    ShowAuthSuccessScreen();
}
catch(AuthenticationFailedException e)
{
    LogError(e);
    ShowAuthFailedScreen();
}
catch(UserLockedOutException e)
{
    LogError(e);
    ShowUserLockedOutScreen();
}
catch(Exception e)
{
    LogError(e);
    ShowGeneralErrorScreen();
}

此外,一个人为的例子。但希望它显示了如何以及为什么你想创建自定义异常。在这种情况下,在 AuthProvider 类被处理每个定制例外的以不同的方式给用户。如果 authenticateUser的方法只是简单地抛出异常,就没有办法来区分之间的不同原因的为什么的异常被抛出。

Again, a contrived example. But hopefully it shows how and why you would want to create custom exceptions. In this case, the user of the AuthProvider class is handling each custom exception in a different way. If the AuthenticateUser method had simply thrown Exception, there would be no way to differentiate between the different reasons why the exception was thrown.

这篇关于.NET抛出自定义异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆