什么时候抛出异常? [英] When to throw an exception?

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

问题描述

我为我的应用程序不希望遇到的每种情况都创建了异常. UserNameNotValidExceptionPasswordNotCorrectException

I have exceptions created for every condition that my application does not expect. UserNameNotValidException, PasswordNotCorrectException etc.

但是,有人告诉我,我不应该为这些情况创建例外.在我的UML中,那些是主流的例外,那么为什么不应该例外呢?

However I was told I should not create exceptions for those conditions. In my UML those ARE exceptions to the main flow, so why should it not be an exception?

创建例外的任何指导或最佳做法?

Any guidance or best practices for creating exceptions?

推荐答案

我的个人指导原则是:当发现当前代码块的基本假设为假时,抛出异常.

My personal guideline is: an exception is thrown when a fundamental assumption of the current code block is found to be false.

示例1:说我有一个函数,该函数应该检查一个任意类,如果该类继承自List<>,则返回true.该函数会询问以下问题:此对象是List的后代吗?"该函数永远不会抛出异常,因为它的操作中没有灰色区域-每个类都可以继承或不继承自List<>,因此答案始终是是"或否".

Example 1: say I have a function which is supposed to examine an arbitrary class and return true if that class inherits from List<>. This function asks the question, "Is this object a descendant of List?" This function should never throw an exception, because there are no gray areas in its operation - every single class either does or does not inherit from List<>, so the answer is always "yes" or "no".

示例2:说我有另一个函数可以检查List <>,如果长度大于50,则返回true,如果长度小于50,则返回false.此功能会询问以下问题:此列表是否包含50多个项目?"但是这个问题是一个假设-它假设给定的对象是一个列表.如果我将其设置为NULL,则该假设为假.在那种情况下,如果该函数返回 true false,则它违反了自己的规则.该函数无法返回任何内容并声称它已正确回答了问题.因此它不会返回-会引发异常.

Example 2: say I have another function which examines a List<> and returns true if its length is more than 50, and false if the length is less. This function asks the question, "Does this list have more than 50 items?" But this question makes an assumption - it assumes that the object it is given is a list. If I hand it a NULL, then that assumption is false. In that case, if the function returns either true or false, then it is breaking its own rules. The function cannot return anything and claim that it answered the question correctly. So it doesn't return - it throws an exception.

这类似于已加载的问题" 逻辑谬误.每个功能都会问一个问题.如果给出了输入,则该问题将成为谬论,然后引发异常.使用返回void的函数很难绘制这条线,但最重要的是:如果违反了函数关于其输入的假设,则应抛出异常而不是正常返回.

This is comparable to the "loaded question" logical fallacy. Every function asks a question. If the input it is given makes that question a fallacy, then throw an exception. This line is harder to draw with functions that return void, but the bottom line is: if the function's assumptions about its inputs are violated, it should throw an exception instead of returning normally.

这个等式的另一面是:如果发现函数经常抛出异常,那么您可能需要完善它们的假设.

The other side of this equation is: if you find your functions throwing exceptions frequently, then you probably need to refine their assumptions.

这篇关于什么时候抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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