什么时候应该用异常,如果不用异常,直接用返回值来代表各种各样的错误是否合理?这个问题曾经在程序语言的学习阶段问过自己,后来也就含糊的理解了。今天看到了MSDN中有这样的一段话,又自己过了一下异常这一个概念,感觉对于加深理解有帮助,MSDN引用如下:
When to Use ExceptionsThree categories of outcomes can occur when a function is called during program execution: normal execution, erroneous execution, or abnormal execution. Each category is described below.
- Normal execution
The function may execute normally and return. Some functions return a result code to the caller, which indicates the outcome of the function. The possible result codes are strictly defined for the function and represent the range of possible outcomes of the function. The result code can indicate success or failure or can even indicate a particular type of failure that is within the normal range of expectations. For example, a file-status function can return a code that indicates that the file does not exist. Note that the term “error code” is not used because a result code represents one of many expected outcomes.
- Erroneous execution
The caller makes some mistake in passing arguments to the function or calls the function in an inappropriate context. This situation causes an error, and it should be detected by an assertion during program development. (For more information on assertions, see Using Assertions.)
- Abnormal execution
Abnormal execution includes situations where conditions outside the program’s control, such as low memory or I/O errors, are influencing the outcome of the function. Abnormal situations should be handled by catching and throwing exceptions.Using exceptions is especially appropriate for abnormal execution.
之后我又自己举了一个例子来解释上面的这段话:
call 去办理宽带 这个函数
- 所谓正常的执行可能返回,办理成功,办理失败(包含某原因,如证件不齐,当天不办理等),这种情况在返回值中体现即可。
- 所谓错误的执行就是你跑到了银行去办理宽带,整个环境和上下文都不对的情况。这种情况是错误的调用了函数,开发期可以纠正,用assert等。
- 所谓异常的执行就是你跑出去办宽带,结果发生了地震了,海啸了等。这情况才需要用到异常。