Java -- Exception Handling

Source: Internet
Author: User

Java -- Exception Handling
Exception inheritance Structure

Let's take a look at the inheritance relationship between common exception classes in Java:

Java divides all exceptions into two types: Error and Exception. They all inherit the Throwable parent class.
Java classifies exceptions into two types: Checked exceptions and Runtime exceptions.

1. Error

Error generally refers to problems related to virtual machines, such as system crashes, virtual machine errors, and dynamic link failures. errors cannot be recovered or cannot be captured, leading to application interruption. Generally, applications should not try to use catch blocks to capture Error objects. When defining this method, you do not need to declare in its throws clause that this method may throw an Error and any subclass of it.

2. Checked

Checked exceptions are all exceptions that can be processed during the compilation phase, so it forces the program to handle all Checked exceptions. Checked exception. This program will encounter an error during compilation and cannot be compiled. This embodies the design philosophy of Java: code without perfect error handling has no chance to be executed.

There are two methods to handle the Checked exception:

(1) If the current method knows how to handle this exception, try... Catch Block to handle this exception.
(2) If the current method does not know how to handle it, the exception is thrown when the method is defined as a declaration.

Familiar Checked exceptions include:

Java. lang. ClassNotFoundException
Java. lang. NoSuchMetodException
Java. io. IOException

3. Runtime

You do not need to handle a Runtime exception. Runtime exceptions are not reported during compilation, but are reported during Runtime, such as null pointer exceptions (NullPointerException). This exception occurs frequently and is complicated to handle, if a declaration or capture is displayed, the readability and Running Efficiency of the program will be greatly affected. Therefore, the system automatically detects and sends them to the default exception handling program. If you have processing requirements, you can also capture them.

The familiar RumtimeException class subclasses are:

Java. lang. ArithmeticException
Java. lang. ArrayStoreExcetpion
Java. lang. ClassCastException
Java. lang. IndexOutOfBoundsException
Java. lang. NullPointerException

Exception Handling syntax

Java's exception mechanism mainly relies on five keywords: try, catch, finally, throw, and throws.

Try keyword

The try keyword is followed by a code block enclosed in curly brackets (the try block cannot be omitted), which contains code that may cause exceptions.

Java 7 automatically closes the try statement of the Resource

Java 7 enhances try. It allows a pair of parentheses to be followed by the try keyword. Parentheses can declare and initialize one or more resources, the resource here refers to the resources (such as database connections and network connections) That must be closed at the end of the program. The try statement automatically closes these resources at the end of the statement.
It should be noted that in order to ensure that the try statement can close resources normally, these resource implementation classes must implement the AutoCloseable or Closeable interfaces. To implement these two interfaces, the close () method must be implemented.
In Java 7, almost all "Resource Classes" (including various types of file IO, JDBC programming interfaces such as Connection and Statement) were rewritten, after rewriting, the resource class implements the AutoCloseable or Closeable interface.
The try statement that automatically closes resources is equivalent to containing an implicit finally block (this finally block is used to close resources). Therefore, this try statement can neither catch Block nor finally block.

Catch keyword

Catch corresponds to the exception type and a code block, which indicates that the catch block is used to process this type of code block. There can be multiple catch blocks.

Java 7 multi-exception capture

Before Java 7, each catch block can capture only one type of exception. from Java 7, a catch block can capture multiple types of exceptions.
When you use a catch Block to catch multiple types of exceptions, note the following two points:
(1) When multiple types of exceptions are captured, multiple types of exceptions are separated by vertical bars (|.
(2) When multiple types of exceptions are captured, the exception variable has implicit final modification (when an exception is caught, there is no implicit final modification). Therefore, the program cannot assign a value to the exception variable.

Finally keyword

Multiple catch blocks can be followed by one finally block. The finally block is used to reclaim physical resources opened in the try block. The exception mechanism ensures that the finally block is always executed.
Even if the return statement finally is used in the try or catch block, the System is executed before the finally block is executed. exit (0); similar to the code used to end JVM, finally code will not be executed.

Throws keywords

The throws keyword is mainly used in method signatures to declare exceptions that may be thrown by this method;
The idea of throwing an exception using throws Declaration is that the current method does not know how to handle this type of exception. The exception should be handled by the upper-level caller; if the main method does not know how to handle this type of exception, you can also use the throws declaration to throw an exception, which will be handed over to the JVM for processing. The JVM can handle exceptions by printing the tracing stack information of exceptions and suspending the program running. This is why the program stops automatically when an exception occurs.

The usage is as follows:

Public static void test () throws IOException {// method body}

When throws is used to declare that an exception is thrown, there is a restriction, that is, a rule of "two smaller" during method Rewriting:
1. The exception type thrown by the subclass method declaration should be the subclass of the exception type thrown by the parent class method declaration or be the same.
2. The subclass method declaration does not throw more exceptions than the parent class method declaration.

Throw keywords

The throw keyword is used to throw an actual exception. throw can be used independently as a statement to throw a specific exception object.

When an error occurs in the program, the system automatically throws an exception. In addition, Java also allows the program to throw an exception and throw the exception by itself using the throw statement.

If you need to throw an exception in the program, you should use the throw statement, which can be used independently. The throw statement throws an instance instead of an exception class, in addition, only one exception can be thrown at a time. The syntax format of the throw statement is as follows:

throw ExceptionInstance;

When the Java runtime receives an exception thrown by the developer, it also terminates the current execution stream and jumps to the catch Block corresponding to the exception to handle the exception. That is to say, whether the system automatically throws an exception or the programmer manually throws an exception, there is no difference in the Java Runtime Environment in exception handling.

If the exception thrown by the throw statement is a Checked exception, the throw statement is either in the try block, explicitly capturing the exception, or in a method with throws declaration throw, that is, the exception is handed over to the caller of the method. If the exception thrown by the throw statement is a Runtime exception, the statement does not need to be placed in the try block, it does not need to be placed in the method with throws declaration throw; the program can explicitly use try... Catch to catch and handle the exception. You can ignore the exception and submit it to the method caller for handling.

Custom exception class

In general, the program rarely throws a system exception, because the exception class name usually contains useful information about the exception. Therefore, when you select to throw an exception, you should select an appropriate exception class to clearly describe the exception. In this case, applications often need to throw custom exceptions.

Custom exceptions must inherit the Exception base class. If you want to customize a Runtime Exception, you must inherit the RuntimeException base class. When defining exception classes, two constructors are usually required. One is a non-parameter constructor, and the other is a constructor with a string parameter, this string will be used as the description of the exception object (that is, the return value of the getMessage () method of the exception object ).
The following example creates a custom exception class.

Public class AuctionException extends Exception {// non-parameter constructor public AuctionException () {}// constructor with a String parameter public AuctionException (String msg) {super (msg );}}

The custom AuctionException Exception class inherits the Exception class and provides a non-parameter constructor and a parameter constructor, in the parameter constructor, you only need to use the super keyword to call the object constructor in the parent class (that is, Exception. This msg is the detailed description of the exception object.

To customize a Runtime Exception, you need to change the Exception base class in the AuctionException. java program to the RuntimeExcetion base class. You do not need to modify it elsewhere.

Try (create object) {} catch (Exception1 | Exception1 | Exception2 e) {} finally {}

The above is the template for abnormal use. Through the above introduction, we can use exceptions to handle our programs, which are more robust and clean.

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.