[JAVA & amp; #183; elementary]: 15. Exception Handling Mechanism

Source: Internet
Author: User

[JAVA & #183; elementary]: 15. Exception Handling Mechanism
Definition

Java exceptions are a mechanism provided by Java to handle errors in programs.

JAVA uses an object-oriented method to handle exceptions. Processing Process:

Throw an exception: if an exception occurs when a method is executed, the method generates an object that represents the exception, stops the current execution path, and submits the exception object to JRE.

Caught exception: After the JRE obtains the exception, it looks for the corresponding code to handle the exception. In the call stack of the method, JRE searches for the method from the method that generates the exception and starts backtracking until the corresponding exception handling code is found.

Category

JDK defines many exception classes, which correspond to a variety of possible exception events. All exception objects are derived from an instance of the Throwable class. If the built-in exception classes do not meet your needs, you can also create your own exception classes.

 

In Java, all exceptions have a common ancestor Throwable ). Throwable specifies the commonalities of any issues that can be transmitted through Java applications through the Exception Propagation mechanism in the code.

Throwable: There are two important subclasses: Exception (Exception) and Error (Error), both of which are important subclasses of Java Exception Handling, each containing a large number of subclasses.

Error (Error): an error that cannot be processed by the program, indicating a serious problem in running the application. Most errors are irrelevant to the operations performed by the code writer, but they indicate problems with JVM (Java Virtual Machine) during code execution. For example, when the JVM does not have the memory resources required to continue the operation, an OutOfMemoryError occurs. When these exceptions occur, the Java Virtual Machine (JVM) generally chooses to terminate the thread.

These errors indicate that the fault occurs on the Virtual machine itself or when the Virtual machine attempts to execute the application, such as a Java Virtual machine running error (Virtual MachineError) or a class definition error (NoClassDefFoundError. These errors are not traceable because they are beyond the control and processing capabilities of the application, and most of them are not allowed when the program is running. For a well-designed application, even if an error occurs, it is essentially not necessary to try to handle the exception caused by it. In Java, the Error is described by the subclass of Error.

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

The Exception class has an important subclass RuntimeException. The RuntimeException class and its subclass indicate errors caused by "common JVM operations. For example, if you try to use a null value to reference an object, the Division is zero, or the array is out of bounds, the runtime exception (NullPointerException, ArithmeticException) and ArrayIndexOutOfBoundException are thrown respectively.

Note: The difference between exceptions and errors: exceptions can be handled by the program itself, but errors cannot be handled.

Generally, Java exceptions (including exceptions and errors) are divided into checked exceptions and unchecked exceptions ).

Queryexception(Exceptions that must be handled by the compiler): exceptions that are easy to occur and reasonable when the right program is running. Although an exception can be queried, it can be predicted to some extent. In addition, once such an exception occurs, some methods must be taken to handle it.

Except for RuntimeException and its subclasses, all other Exception classes and their subclasses are queryable exceptions. This exception is characteristic of the Java compiler checking it. That is to say, when such exceptions may occur in the program, either catch it with a try-catch statement or throws it with a throws clause declaration, otherwise, compilation fails.

Error not found(Exceptions that the compiler does not require to forcibly handle): including runtime exceptions (RuntimeException and its subclass) and errors (errors ).

Exceptions are classified into two types: runtime exceptions and non-runtime exceptions (compilation exceptions ). The program should try to handle these exceptions.

Runtime exception: They are all RuntimeException classes and their subclass exceptions, such as NullPointerException (NULL pointer exception) and IndexOutOfBoundsException (subscript out-of-bounds exception). These exceptions are non-check exceptions and can be captured and processed in programs, or not. These exceptions are generally caused by program logic errors. The program should avoid such exceptions logically.

The runtime exception is characteristic that the Java compiler does not check it. That is to say, when such exceptions may occur in the program, even if the try-catch statement is not used to catch it, it is not thrown by the throws clause declaration, it will also be compiled.

Non-runtime exception(Compilation Exception): it is an Exception other than RuntimeException and belongs to the Exception class and its subclass. From the perspective of program syntax, it is an exception that must be processed. If it is not processed, the program cannot be compiled. Such as IOException, SQLException, and user-defined Exception. Generally, no custom check Exception occurs.

Custom exception: The Java built-in exception classes can be used to describe most of the exceptions that occur during programming. In addition, you can customize exceptions. You only need to inherit the Exception class to customize the Exception class.

To use a custom exception class in a program, follow these steps.

(1) create a custom exception class.

(2) throw an exception object through the throw keyword in the method.

(3) If an exception is handled in the method currently thrown, you can use the try-catch statement to capture and handle the exception; otherwise, the throws keyword is used in the method declaration to indicate the exception to be thrown to the method caller and continue the next operation.

(4) capture and handle exceptions in callers with abnormal methods.

Exception chain

1) if quotient (3,-1) is called, a MyException exception will occur and the program is transferred to the catch (MyException e) code block for execution;

2) If quotient (5, 0) is called, The ArithmeticException exception will be caused by the "divisor 0" error. It is a runtime exception class and is automatically thrown by the Java runtime system. The quotient () method does not capture the ArithmeticException exception. During Java runtime, the system will check the main method along the method call stack and upload the thrown exception to the quotient () method Caller:

Int result = quotient (a, B); // call the quotient () method ()

Because this statement is in the try monitoring area, the ArithmeticException that is returned with a division of 0 is thrown by the Java runtime system and matches the catch clause:

 

Catch (ArithmeticException e) {// handle ArithmeticException exception System. out. println ("the divisor cannot be 0"); // output prompt information}

 

The output result is "the divisor cannot be 0 ". Java is a processing mechanism that transfers exception information upwards to form an exception chain.

The queryable exception thrown by the Java method is passed to the calling method with processing capability based on the call stack and along the hierarchy of method calls, up to the main method. If the exception is passed to the main method, but the main method does not have the processing capability and throws the exception through throws declaration, a compilation error may occur.

3) if other exceptions occur, catch (Exception e) will be used to catch exceptions. Because Exception is the parent class of all Exception classes, if you put the catch (Exception e) code block before the other two code blocks, the subsequent code blocks will never be executed, and it makes no sense, therefore, the order of catch statements cannot be changed.

Processing Mechanism

In Java applications, the exception handling mechanism is: throw an exception and catch an exception.

Throw an exception: When a method error causes an exception, the method creates an exception object and delivers the system during running. The exception object contains exception information such as the exception type and program status when the exception occurs. The runtime system is responsible for finding and executing the code to handle exceptions.

Capture exceptions: After the method throws an exception, the runtime system will turn to the exception handler ). A potential exception processor is a set of methods that are stored in the call stack in sequence when an exception occurs. When the exception type that the exception processor can handle matches the exception type thrown by the method, it is a suitable exception processor. During the runtime, the system starts from the abnormal method and re-queries the method in the stack until it finds and executes the method containing the appropriate exception processor. When the runtime system traverses the call stack and does not find a suitable exception processor, the runtime system terminates. At the same time, it means the termination of the Java program.

Java technology requires different Exception Handling Methods for runtime exceptions, errors, or queryable exceptions.

Due to the inaccessibility of runtime exceptions, Java stipulates that runtime exceptions will be automatically thrown by the Java runtime system for more reasonable and easier application implementation, allows applications to ignore runtime exceptions.

For errors that may occur during method running, when the running method does not want to capture, Java allows this method to not throw a declaration. Because most Error exceptions are not allowed to happen, and they are also exceptions that should not be captured by reasonable applications.

For all traceable exceptions, Java requires that a method must be caught or declared to be excluded from the thrown method. That is to say, when a method does not capture queryable exceptions, it must declare that an exception will be thrown.

Methods that can capture exceptions must provide a consistent type of exception processor. The caught exception may be an exception caused and thrown by a statement, or an exception thrown by a calling method or a Java runtime system. That is to say, the exception that a method can capture must be an exception thrown by Java code in a certain place. In short, exceptions are always thrown first and captured later.

Any Java code can throw an exception, such as self-written code, code from the Java Development Environment package, or the Java runtime system. No matter who you are, you can throw an exception through the Java throw statement.

Any exception thrown from the method must use the throws clause.

Catch exceptions are implemented through try-catch or try-catch-finally statements.

In general, Java rules: For queryable exceptions, they must be caught or declared to be thrown. Ignore unqueryruntimeexception and Error.


Method:

A) String toString (); used to obtain the name and cause of the exception object.

B) String getMessage (); used to obtain only the cause of the exception object.

C) void printStackTrace (); used to print all information about the exception object (name, reason, location ).

Business Philosophy

No exception, no program. I believe that there will be different exceptions in every program, and our program will continuously tune bugs for a period of time. I don't think exceptions are a bad thing, but they can promote our understanding of the business.

Enjoy the thoughts brought about by exceptions, and we will make rapid progress!

Related Article

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.