首先,我知道标准答案是永远不会将异常用于流量控制。虽然我完全同意这一点,但我一直在思考我有时会做的事情,我将用以下伪代码来描述:
try
string keyboardInput = read()
int number = int.parse(keyboardInput)
//the conversion succeeds
if(number >= 1000)
//That's not what I asked for. The message to display to the user
//is already in the catch-block below.
throw new NumberFormatException() //well, there IS something wrong with the number...
catch(NumberFormatException ex) //the user entered text
print("Please enter a valid number below 1000.")
首先,以非常抽象的方式来举这个例子。这不一定要发生。情况很简单:
用户输入需要受到约束,并且可能以两种方式出错,一种是语言定义的抛出异常,另一种是检查。用户以相同的方式报告这两个错误,因为他们不需要知道导致它的技术差异。
我想了几种方法来解决它。首先,最好抛出一个定制的异常。然后我面临的问题是,如果我在本地捕获它,如何处理另一个异常?在 se 中,自定义异常将导致第二个 catch 块,其中消息也将被复制到其中。我的解决方案:
//number is wrong
throw new MyException()
catch(NumberFormatException ex)
throw new MyException()
catch(MyException ex) {
print("Please enter...")
异常名称的含义就是这里的一切。这种自定义异常的应用程序被广泛接受,但基本上我没有做任何与第一种方式不同的事情:我被迫进入一个 catch-block,尽管抛出一个自定义异常而不是标准库异常。
将异常抛出到调用方法的相同方法(因此没有自定义异常的 catch 块)似乎更有意义。我的方法在技术上可能有两种方式出错,但本质上是一种方式:错误的用户输入。因此,人们会编写一个UserInputException
并让方法抛出这个。新问题:如果这是应用程序的主要方法怎么办?
我目前并没有为实现这种行为的特定应用程序而苦苦挣扎,我的问题纯粹是理论上的和非语言特定的。
解决这个问题的最佳方法是什么?