Java Basic teaching Java exception mechanism

Source: Internet
Author: User
Tags stack trace throw exception throwable

Today we mainly talk about the Java anomaly mechanism. Set up Java Learning Group 457036818, you can exchange

I. The concept of anomalies and Java exception architectures

An exception is an error that occurs while the program is running. This article mainly teaches some of the exception handling of rolling and Java languages. The exception processing framework of Java language is an important embodiment of the robustness of Java language. Java treats exceptions as objects, and defines a base class java.lang.Throwable as a superclass of all exceptions. Many exception classes have been defined in the Java API, and these exception classes fall into two main categories, error errors and exception exception. The Java exception architecture is tree-like, and its hierarchy is shown in Figure 1:

650) this.width=650; "class=" Alignnone size-full wp-image-431 "title=" Java Exception Architecture "alt=" 1213HF9AP1M19 "src="/http S3.51cto.com/wyfs02/m02/6c/fa/wkiol1vzf_rrq07waab8gvcd0q4055.jpg "width=" 367 "height=" 195 "/>

Figure 1 Java Exception architecture

Thorwable class for all exceptions and errors, there are two subclasses of error and exception, respectively, representing errors and exceptions. The exception class Exception is divided into run-time exceptions (RuntimeException) and non-runtime exceptions, the two exceptions are very different, also known as the non-check exception (unchecked Exception) and check the exception (Checked Exception). The differences and linkages between these exceptions are described in detail below:

1, errors and exception error is the program can not handle the mistakes, such as OutOfMemoryError, Threaddeath and so on. When these exceptions occur, the Java Virtual machine (JVM) typically chooses to terminate the thread.
Exception is an exception that the program itself can handle, which is divided into two classes of runtime exceptions and non-runtime exceptions. These exceptions should be handled as much as possible in the program.

2. Run-time exceptions and non-runtime exceptions

Run-time exceptions are runtimeexception classes and their subclass exceptions, such as NullPointerException, Indexoutofboundsexception, and so on, which are not checked for exceptions, can be selected for capture processing in the program, or can not be processed. These exceptions are usually caused by a program logic error, and the program should avoid this kind of exception as much as possible from a logical point of view.

A non-runtime exception is an exception that is runtimeexception except that the type belongs to the exception class and its subclasses. From the point of view of the program syntax is the exception that must be handled, and if not handled, the program cannot be compiled through. such as IOException, SqlException, and user-defined exception exceptions, generally do not customize check exceptions.

Second, abnormal capture and processing

Java exception capture and processing is a difficult thing to grasp, if handled improperly, not only will make the program code readability greatly reduced, and caused the system performance is low, even caused some difficult to find errors.

Java exception handling involves five keywords, namely: try, catch, finally, throw, throws. Here is a brief introduction, through the understanding of these five keywords, master the basic exception processing knowledge.

1. Basic syntax for exception handling
In Java, the complete syntax for exception handling is:
try{
Program code (trying to run)
}catch (variable name for exception type exception) {
Exception handling code
}finally{
The code that is always executed before the exception occurs, before the method returns
}

The syntax above has three blocks of code:
A try statement block, which indicates that the code in the TRY statement block is monitored for exception when an exception is thrown, and throws an exception object when the code is being run.

The catch statement block captures the exception that occurs in the try code block and does exception handling in its code block, which takes a parameter of type Throwable, which indicates that the exception type can be caught. When an exception occurs in a try, the catch catches the exception that occurs and matches its own exception type, executes the code in the Catch block, and points the catch block argument to the thrown exception object. A catch statement can have multiple occurrences that match one of the many exceptions, and once the match is made, it is no longer attempted to match another catch block. The exception object can be used to obtain complete JVM stack information at the time of the exception, as well as the exception information and the reason for the exception to occur.

A finally statement block is a block of statements immediately following a catch statement, which is always executed before the method returns, regardless of whether the try statement block has an exception. And this block of statements is always executed before the method returns. The purpose is to give the procedure a chance to remedy.     This also embodies the robustness of the Java language. 2, try, catch, finally three statement block should pay attention to the problem
The first, try, catch, finally three block of statements can not be used alone, the three may be composed of try...catch...finally, Try...catch, try...finally three structures, catch statements can have one or more, The finally statement has at most one.
The scope of the variables in the second, try, catch, finally three code blocks is within the code block, independent of each other and not accessible to each other. If you want to be accessible in three blocks, you need to define the variables outside of those blocks.
Third, multiple catch blocks, only one of the exception classes is matched and the catch block code is executed, and no other catch blocks are executed, and the order of matching catch statements is from top to bottom.

    3, throw, throws keyword
    throw keyword is used inside the method body to throw an exception of type Throwable. If you throw a check exception, you should also declare the type of exception that the method might throw on the method header. The caller of the method must also check the exception that is thrown by the handle. If all of the methods are thrown at layers, the JVM will eventually be processed and the processing is simple, which is to print the exception message and stack information. If an error or runtimeexception is thrown, the caller of the method can choose to handle the exception. The translation of the exception is described below. The     throws keyword is used in the method declaration section outside the method body to declare that the method may throw some exceptions. Only if a check exception is thrown, the caller of the method must handle or re-throw the exception. When the caller of the method is unable to handle the exception, it should continue to throw, rather than swallowed generally print the stack information in the catch block and do a little bit of processing. Here's a simple example to see how to use these two keywords:
         public static void Test3 () throws exception{
     //Throw a check exception
             throw new Exception ("Exception in Method Test3");
       } 
    3, common methods in the Throwable class
     Getcause (): Returns the reason for throwing an exception. If cause does not exist or is unknown, NULL is returned.
    getMessage (): Returns the message information for the exception.
    Printstacktrace (): The object's stack trace is output to the error output stream as the value of the field System.err.

Iii. general principles of exception handling

1, can deal with the early processing, throw not to be able to deal with the idea of digestion or conversion to runtimeexception processing. Because it is problematic for an application system to throw a large number of exceptions, it should be possible to control the occurrence of exceptions from the point of view of the program development.
2, for inspection anomalies, if not effective processing, it is better to convert to runtimeexception thrown. This also allows the upper-level code to have a choice-can be handled or not processed.
3, for an application system, should have their own set of exception processing framework, so when the exception occurs, you can also get a unified processing style, will be elegant abnormal information feedback to the user.

Iv. abnormal translation and abnormal chain
1, the principle of abnormal translation

The so-called abnormal translation is to convert an exception to another new exception, perhaps the new exception is more accurate to express the program exception.

In Java, there is a concept is the exception reason, the exception causes the exception of the current throw exception object, almost all the exception with the cause of the construction method using the Throwable type parameters, which provides a direct support for the translation of the exception, Because any form of exceptions and errors are throwable subclasses. For example, to convert SqlException to another new exception daoexception, you can write:

Customize an exception Daoexception first:

public class Daoexception extends RuntimeException {
(Part of the code is omitted)
Public daoexception (String message, throwable cause) {
Super (message, cause);
}
}
For example, there is a SqlException type of exception object E, to convert to Daoexception, you can write:

Daoexception Daoex = new Daoexception ("SQL Exception", e);

Exception translation is for all classes that inherit the Throwable superclass, and from a programmatic point of view, the subclasses can be transformed from one to the other. However, from the perspective of rationality and system design, the exception can be divided into three categories: Error, Exception, RuntimeException, the author believes that a reasonable translation diagram should be 2:

650) this.width=650; "class=" Alignnone size-full wp-image-433 "title=" Exception translation "alt=" 1213hfa2102w24 "src="/http S3.51cto.com/wyfs02/m00/6c/ff/wkiom1vzfqfsyyuwaabjoa2pucw105.jpg "width=" 305 "height=" 169 "/>

Figure 2 Exception translation

Why did you do it? In the author's opinion, there is a set of philosophical ideas about the handling of anomalies: for an application system, any exception or error that occurs to the operating user is the system "runtime" exception, which is the exception of this application system. This is also the guiding principle of abnormal translation and application System anomaly framework design. Many of the negative effects of non-check exceptions are dealt with in the system, and one of the most important aspects is that the code is less readable, the programming is complex, and the code for exception handling is very feeble. Therefore, it is necessary to convert these check exceptions exception and error errors to runtimeexception exceptions, allowing the programmer to decide whether to capture and handle the exceptions that occur, depending on the situation.

The three lines in the figure identify the direction of the conversion in three different situations:

①:error to Exception: Converts the error to an exception and continues to throw. For example, in the Spring web framework, you will org.springframework.web.servlet.DispatcherServlet the Dodispatch () method, Translates the captured error to a nestedservletexception exception. This is done to maximize the negative impact of the error. Because an error is often a serious mistake, it can cause the system to hang.

②:exception to runtimeexception: Converting a check exception to RuntimeException can make program code more elegant, allowing developers to focus on managers designing more reasonable program code, which in turn increases the likelihood of system anomalies.

③:error to RuntimeException: The purpose is the same. Translating all exceptions and errors into non-checking exceptions can make the code more concise and facilitate uniform handling of error and exception information.

1. Abnormal chain

The exception chain as its name implies that the reason for the occurrence of a string up, that is, the bottom of the exception information to the upper layer, so that the layers thrown. A simple model is given in the Java API documentation:

try {
Lowlevelop ();
} catch (Lowlevelexception le) {
Throw (highlevelexception)
New Highlevelexception (). Initcause (LE);
}

When the program captures an underlying exception, le, in the processing section, chooses to continue to throw a higher-level new exception to the caller of this method. This causes the exception to pass through the layer. In this way, the exception recursively called the Getcause () method at the upper level can traverse the exception causes of each layer. This is how the Java exception chain works. The actual application of the abnormal chain is very few, when the abnormal time is not a good attention, the upper layer to get these anomalies and can nai? And the exception is thrown on the layer by a lot of resources, because to save a complete exception chain information.

V. Design an efficient and reasonable exception handling framework

For an application, any exception that occurs to the user appears to be an exception within the application system. Therefore, a set of application system exception framework should be designed to deal with all the exceptions during the system operation.

Based on this view, it is possible to design an application-system anomaly such as appexception. And for the user, these exceptions occur when running the application system, so appexception should inherit runtimeexception so that all other exceptions in the system are translated into appexception, and when the exception occurs, the first Receive Appexcetpion and do a unified processing. Draw Exception Handling Framework 3:

650) this.width=650; "class=" Alignnone size-full wp-image-434 "title=" Application system Exception Handling framework "alt=" 1213HFAA031H5 "src="/http S3.51cto.com/wyfs02/m02/6c/fa/wkiol1vzgesghb9faafdhy78v0w295.jpg "width=" 471 "height=" 358 "/>

Figure 31 Exception handling framework for application Systems

In this design, Appruntimeexception is the base class for system exceptions, which only throws this exception, which can be received by the front-end (client), and when an exception occurs, the client's related components capture and process these exceptions, presenting "friendly" information to the customer.
In the appruntimeexception, there are all kinds of anomalies and errors, eventually translated into appruntimeexception,appruntimeexception below can also design some other sub-class exceptions, such as Appdaoexception, Otherexception and so on, which are flexibly handled according to the actual needs. The next step is how to convert the captured primitive exceptions, such as SQLException, Hibernateexception, to a more advanced point appdaoexception.

The good thing about exception frame design is that all exceptions in spring,spring can be represented by org.springframework.core.NestedRuntimeException, and the base class inherits the RuntimeException. The spring framework is huge, so a lot of nestedruntimeexception are designed, and the tools for exception conversion are very good design ideas.

Vi. Summary of Java exception handling

Review the full text and summarize the main points of Java exception handling:

1, the exception is the program running process errors, in the Java class to describe, with the object to represent the specific exception. Java distinguishes it from error and exception,error are errors that the program is unable to handle, and exception is the error that the program can handle. Exception handling is for the robustness of the program.
2. Java exception classes come from Java API definitions and user extensions. Exceptions can be translated by inheriting the Java API Exception class.
3, the exception can be processed on the processing, can not be processed on the throw, the final unhandled exception JVM will be processed.
4, abnormal can be spread, can also be translated, but should be based on the need to choose a reasonable direction of abnormal translation.
5, for an application system, it is very important to design a set of good exception handling system. This should be taken into account when designing the system.

This article is from the Java Learning Video tutorial blog, so be sure to keep this source http://10239772.blog.51cto.com/10229772/1652293

Java Basic teaching Java exception mechanism

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.