java--exception (i)

Source: Internet
Author: User
Tags class definition throwable

First, what is an anomaly?

Exception refers to the various conditions, such as: file cannot be found, network connection failure, illegal parameters and so on. An exception is an event that interferes with the normal instruction flow during the program's run. ( a flow of instruction that causes a program to break )

Java describes various kinds of exceptions through the many subclasses of the Throwable class in the API. Thus, Java exceptions are objects, examples of throwable subclasses, and describe error conditions that occur in a piece of code. An error throws an exception when the condition is generated.

Java Exception class hierarchy diagram:

    

In Java, all exceptions have a common ancestor throwable (can be thrown). Throwable specifies the commonality of any problem that can be transmitted through a Java application using the exception propagation mechanism in the code.
Throwable: There are two important subclasses: Exception (Exception) and error (Errors), both of which are important subclasses of Java exception handling, each of which contains a large number of subclasses.

Error (Error): A bug that the program cannot handle, indicating a more serious problem in running the application. Most errors are unrelated to what the code writer does, and represent a problem with the JVM (the Java virtual machine) that is running the code. For example, the Java Virtual machine runs the error (virtual Machineerror) and OutOfMemoryError occurs when the JVM no longer has the memory resources required to continue the operation. When these exceptions occur, the Java Virtual machine (JVM) typically chooses to terminate the thread.

These errors indicate that the failure occurred on the virtual machine itself, or when the virtual machine attempted to execute the application, such as a Java Virtual machine run error (virtual Machineerror), a class definition error (NOCLASSDEFFOUNDERROR), and so on. These errors are not available because they are outside the control and processing power of the application and are mostly not allowed when the program is running. For a well-designed application, even if it does, it should not be an attempt to deal with the anomalies that it causes. In Java, errors are described by the subclasses of the error.

Exception (Exception): is an exception that the program itself can handle.

The Exception class has an important subclass runtimeexception. The RuntimeException class and its subclasses represent errors thrown by the JVM common operation. For example, if you attempt to use null object references, divide by zero, or array out of bounds, the run-time exceptions (NullPointerException, ArithmeticException), and arrayindexoutofboundexception are raised respectively.

Note: Exceptions and errors are different: Exceptions can be handled by the program itself, and errors cannot be handled.

In general, Java exceptions (including exception and error) are categorized as checked exceptions and non-checked exceptions (unchecked exceptions).
can check exceptions (compiler requirements must be disposed of exceptions): The correct program in operation, it is easy to appear, reasonable tolerance of abnormal conditions. Although the abnormal condition can be checked, it can be predicted to some extent, and in the event of such abnormal situation, it must be handled in some way.

In addition to RuntimeException and its subclasses, other exception classes and their subclasses belong to the exception-checking. This exception is characterized by the Java compiler checking it, that is, when such an exception can occur in a program, either by capturing it with a try-catch statement or by declaring it with a throws clause, or the compilation will not pass.

exception not checked (compiler does not require forced disposition of exceptions): Includes run-time exceptions (RuntimeException with its subclasses) and errors (error).

Exception This exception is divided into two major classes of runtime exceptions and non-runtime exceptions (compilation exceptions). These exceptions should be handled as much as possible in the program.

Run-time Exceptions: both the RuntimeException class and its subclass exceptions, such as nullpointerexception (null pointer exception), indexoutofboundsexception (subscript out-of-bounds exception), etc. These exceptions are not checked for exceptions, the program can choose to capture the processing, or it 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.

  Please explain Error and the Exception the difference?

· Error: Indicates that the JVM system error, at this time the program has not been executed, so the user can not process;

· Exception: Represents an exception that occurs during all program runs and can be handled by the user.

Second, the initial anomaly

 

 

Now that we find that the program has an exception that will cause the program to break, the problem is that even if an exception occurs, we expect the program to execute properly.

Third, handling exceptions

Common code structure for exception handling

try{
//Business code
... ..
}catch (Exceptiontype ex) {
//handling code After an exception occurs
... ..
}catch (Exceptiontype ex) {
//can exist multiple catch for exception handling
... .. } finally{
//Whether or not an exception is caught, the finally code will be executed
//The code here is often used to recycle resources
... ..

Generally in the actual application process can have three kinds of basic forms: try/catch;try/finally;try/catch/finally.

A pair of curly braces after the keyword try will wrap a piece of code that may have an exception, called the monitoring area. An exception object is created when the Java method has an exception during the run. The exception is thrown outside the monitoring area by the Java Runtime system trying to find a matching catch clause to catch the exception. If there is a matching catch clause, the exception-handling code is run, the Try-catch statement ends, and there is no matching catch clause after the exception, and the program throws an exception.

If a finally clause exists, it is executed regardless of whether the program exception is triggered or captured, and is commonly used to perform cleanup operations on resources for resource recycling.

The principle of matching is that if the thrown exception object belongs to the exception class of the Catch clause, or to the subclass of the exception class, the generated exception object is considered to match the type of exception caught by the catch block.

Example 1: Exception handling

  

Example 2: Using multiple catch handling exceptions

 Public classTestdemo { Public Static voidMain (String args[]) {System.out.println ("1, the division calculation begins. ") ; Try {                            //receive parameter data and convert it to int type data                            intx = Integer.parseint (args[0]) ; inty = Integer.parseint (args[1]) ; System.out.println ("2, Division Calculation:" + (X/y)); System.out.println ("******************") ; } Catch(ArithmeticException e) {System.out.println ("〖arithmeticexception, arithmetic exception. 〗") ;                   E.printstacktrace (); } Catch(arrayindexoutofboundsexception e) {System.out.println ("ArrayIndexOutOfBoundsException, array out-of-bounds exception. ") ;                   E.printstacktrace (); } Catch(NumberFormatException e) {System.out.println ("NumberFormatException, data conversion exception. ") ;                   E.printstacktrace (); } finally{System.out.println ("* * * Regardless of whether there are exceptions to execute. ") ; } System.out.println ("3. The end of the division calculation. ") ; }}

The E.printstacktrace () method makes verbose exception output.

  Note : When using multiple catches for processing, exceptions that capture a small range must be placed before an exception that captures a large range, or a compilation error will occur.

Iv. exception handling mechanism

1, when the program in the process of running an exception, then automatically by the JVM according to the resulting exception type, automatically instantiate a matching Exception class object (the object can be referenced to pass, can contain a lot of information);

2, at this time the JVM will determine whether there is a try statement in the code of the exception to the exception of the capture;

3. If there is a try statement now, the instance of the exception class will be captured by a try, and if there is no try, then there is no exception handling, then the exception will be given to the JVM by default processing

4, if there is a try, then the try to catch the exception, and then the try statement after each catch to match, if the current catch does not match, it will be given to the subsequent catch continue to match;

5, if there is a successful catch matching the code in the statement to handle the exception, if there is no matching catch, then the exception will be assigned to the JVM default processing;

6, if there is a finally code in the program now, then all catch can not be handled exception, will determine whether there is a finally code, if there is finally, then execute the program in finally and then to the JVM default processing, After all the catch has been executed, it is also determined whether there is a finally;

7, into the finally code there are two cases, one is not processed, after the completion of the finally code, after the program will no longer execute, and if the exception has been processed, continue to execute finally after the program.

Through the above analysis, it can be found that the so-called exception processing and catch matching exception, then very similar to the method of the parameter transfer process. The only difference is that the method name at this time is uniformly used by the Catch keyword representation, and all the calling process is done automatically by the try, so since it is a parameter passing process, you can follow the previously learned object automatically upward transformation of the way to handle, all the exception classes are exception subclasses , then all exceptions can be handled using exception.

Summary: The rule of exception control flow is that if both a catch clause and a finally clause exist, the control flow is first transferred to the catch clause, then the jump executes the finally clause, and if there is no catch clause, the control flow is transferred to the finally clause.

java--exception (i)

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.