Analysis of exception and exception handling framework

Source: Internet
Author: User
Tags exception handling advantage

Transferred from: http://www.ibm.com/developerworks/cn/java/j-lo-exceptionframework/index.html

http://www.ibm.com/developerworks/cn/java/j-lo-exception/

Http://www.packtpub.com/article/exceptions-and-logging-in-apache-struts2

The processing criterion http://www.jz123.cn/text/1925556.html of the Java EE System anomaly

10 ways to handle exception handling in Java http://blog.csdn.net/caihongshijie6/article/details/8759895

Classification of Java exception handling

Java exceptions can be categorized as detectable exceptions, non-detection exceptions, and custom exceptions.

Detectable exceptions

A detectable exception is validated by the compiler, and for any method that declares an exception, the compiler enforces a processing or claim rule, for example: Sqlexecption This exception is a detection exception. When you connect to JDBC, the exception is not caught and the compiler does not allow compilation.

Non-detection exception

Non-detection exceptions do not follow processing or claim rules. When such an exception is generated, it is not necessary to take any appropriate action, and the compiler does not check whether such an exception has been resolved. For example: An array is 3 lengths, and when you use Subscript 3 o'clock, an array subscript bounds exception is generated. This exception JVM does not detect, it depends on the programmer to judge. There are two main classes that define a non-detection exception: RuntimeException and Error.

The Error subclasses are non-detection exceptions because they cannot be predicted when they occur. If the Java application is out of memory, OutOfMemoryError may occur at any time, and the cause is generally not a special call to the application, but a problem for the JVM itself. In addition, Error generally indicates a serious problem that the application cannot resolve.

The RuntimeException class is also a non-detection exception because the runtime exceptions thrown by ordinary JVM operations can occur at any time, and such exceptions are typically raised by specific operations. However, these operations occur frequently in Java applications. Therefore, they are not limited by the compiler's checking and processing or declaring rules.

Custom exceptions

Custom exceptions are meant to represent some of the error types of your application, providing new meaning for one or more issues that your code might occur. You can display the similarity of errors between multiple locations in your code, or you can differentiate one or more errors that might occur when the code is running, or give specific meaning to a set of errors in your application. For example, when working with a queue, there are two possible scenarios: an empty queue when an attempt is made to delete an element, and an attempt to add an element when the queue is full. You need to customize two exceptions to handle both cases.

Back to top of page

Java exception handling principles and taboos

The Java exception handling principle handles exceptions as much as possible

To handle exceptions as much as possible, consider declaring exceptions if the condition does not allow you to complete processing in your own code. If a person is to avoid handling exceptions in code, it is a false and dependent practice to make declarations only. Specific problem-specific solutions

Part of the advantage of exceptions is the ability to provide different processing operations for different types of problems. The key to effective exception handling is to identify specific fault scenarios and develop specific behaviors that address this scenario. To take advantage of exception handling capabilities, you need to build specific processor blocks for specific types of problems. Log exceptions that may affect the application's running

At a minimum, take some permanent steps to document the exceptions that may affect the operation of the application. Ideally, of course, it is the first time to resolve the underlying problem that caused the exception. However, regardless of the processing operation, the underlying critical issues should generally be documented. Although this is a simple operation, it can help you to keep track of the causes of complex problems in your application with little time. Convert an exception to a business context based on the situation

To notify an application-specific issue, it is necessary to convert the application to a different form. Code is easier to maintain if the exception is represented by a business-specific state. In a sense, whenever an exception is passed to a different context (that is, another technology layer), the exception should be converted to a form that is meaningful to the new context.

Java exception handling taboo generally do not ignore exceptions

In the exception handling block, one of the most dangerous moves is to handle the exception "without notice". As shown in the following example:

1   try{
2       class.forname ("Business.domain.Customer");
3   }
4   catch (ClassNotFoundException exc) {}

It is often possible to see similar blocks of code in a block of code. There are people who like to write code with a simple and quick way of writing empty processor blocks, and "self-comforting" claims to be ready to add recovery code in "late", but this "late" becomes "endless".

There is no harm in this practice. If the exception does not have any negative impact on other parts of the application, it is not. But this is often not the case, and exceptions disrupt the state of the application. At this point, such code is tantamount to deceiving.

If this approach is less influential, the application may behave strangely. For example, a value for an application setting is missing, or the GUI fails. If the problem is serious, the application may have a major problem because the exception is not logged with the original point of failure, which is difficult to handle, such as duplicate nullpointerexceptions.

If you take steps to record the caught exception, you are not likely to experience this problem. In fact, unless the validation exception has no effect on the rest of the code, it must be recorded at least. Further, never overlook the problem; otherwise, the risks are high and unpredictable consequences can be caused in the late stages. Do not use covered exception handling blocks

Another dangerous treatment is the overlay processor (blanket handler). The basic structure of the code is as follows:

1   try{
2     //...
3   }
4   catch (Exception e) {
5     //...
6   }

There are two prerequisites for using an overlay exception handling block:

1. There is only one type of problem in the code.

This may be true, but even then, you should not use covered exception handling to capture more specific exception forms that are advantageous to the pros and cons.

2. A single recovery operation is always applicable.

This is almost absolute error. There is hardly any way to universal and respond to any problems that arise.

Analyze what happens when you write code like this. Everything works as long as the method constantly throws the expected set of exceptions. However, if you throw an unexpected exception, you cannot see the action you want to take. When the overlay processor performs a stereotyped task on the new Exception class, it can only indirectly see the result of the exception being processed. If the code does not print or record a statement, the result is not visible at all.

Worse, when the code changes, the overlay processor will continue to work on all new exception types and handle all types in the same way. Generally do not convert specific exceptions to more general exceptions

A bad practice when converting a specific exception to a more generic exception. In general, this cancels the context that is generated when the exception was initially thrown, which is more difficult to handle when the exception is passed to other locations in the system. See the following example:

1   try{
2     //Error-prone code
3   }
4   catch (IOException e) {
5      String msg = "If You Didn ' t has a problem before,you do now! ";
6      throw new Exception (msg);
7   }

Because there is no information about the original exception, the processor block cannot determine the cause of the problem or how to correct the problem. Do not handle exceptions that can be avoided

For some exception types, you don't actually have to deal with them at all. Normally run-time exceptions fall into this category. You do not have to resort to exception handling when dealing with problems such as null pointers or data indexes.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.