`

异常处理框架

    博客分类:
  • java
 
阅读更多

The Nature of Exceptions


Broadly speaking, there are three different situations that cause exceptions to be thrown:

    Exceptions due to programming errors : In this category, exceptions are generated due to programming errors (e.g., NullPointerException and IllegalArgumentException). The client code usually cannot do anything about programming errors.

    Exceptions due to client code errors : Client code attempts something not allowed by the API, and thereby violates its contract. The client can take some alternative course of action, if there is useful information provided in the exception. For example: an exception is thrown while parsing an XML document that is not well-formed. The exception contains useful information about the location in the XML document that causes the problem. The client can use this information to take recovery steps.

    Exceptions due to resource failures: Exceptions that get generated when resources fail. For example: the system runs out of memory or a network connection fails. The client's response to resource failures is context-driven. The client can retry the operation after some time or just log the resource failure and bring the application to a halt.

 

Java defines two kinds of exceptions:

  • Checked exceptions: Exceptions that inherit from the Exception class are checked exceptions. Client code has to handle the checked exceptions thrown by the API, either in a catch clause or by forwarding it outward with the throws clause.

  • Unchecked exceptions: RuntimeException also extends from Exception . However, all of the exceptions that inherit from RuntimeException get special treatment. There is no requirement for the client code to deal with them, and hence they are called unchecked exceptions.

Java的异常处理机制具有的优势:
给错误进行了统一的分类,通过扩展Exception类或其子类来实现。从而避免了相同的错误可能在不同的方法中具有不同的错误信息。在不同的方法中出现相同的错误时,只需要throw 相同的异常对象即可。
获得更为详细的错误信息。通过异常类,可以给异常更为详细,对用户更为有用的错误信息。以便于用户进行跟踪和调试程序。
把正确的返回结果与错误信息分离。降低了程序的复杂度。调用者无需要对返回结果进行更多的了解。
强制调用者进行异常处理,提高程序的质量。当一个方法声明需要抛出一个异常时,那么调用者必须使用try….catch块对异常进行处理。当然调用者也可以让异常继续往上一层抛出。

 

我们的异常处理框架

在具体的业务中,会涉及到业务返回错误的情形。比如用户登录需要验证用户名和密码,如果正确的时候,方法返回用户的uid,如果错误,返回对应的错误信息,比如用户名不存在,密码不匹配等。

为了分离正确返回结果和错误的情形,这里定义业务异常,由外部程序进行捕获与处理是恰当的。其中业务异常是一个checkedException,强制外部进行处理。

 

对于一个模块,发生如下的情形时,应当抛出RuntimeException:

  • 访问的资源发生错误,例如网络通信失败;(如有需要,网络通信失败可以进行重试)数据库访问失败;
  • 调用其他系统的方法,返回未知的业务代码;(这种情况应当详细记录,便于未来修改程序)
  • 其他无法处理的异常。

中间程序对异常的处理:如果一个业务异常能够进行处理的话,则不抛出,内部进行处理;否则直接抛出;

 

顶层容器对异常的处理:业务异常通常决定了流程,需要进行处理;同时采用统一的处理机制来处理RuntimeException,比如跳转到指定的错误页面。

 

 

异常的记录规则:

RuntimeException异常应该在最初产生的位置进行记录!业务异常能够处理的话不必进行记录,属于流程的一部分。

顶层容器需要对所有RuntimeException进行记录,因为他们可能从多个渠道产生。

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics