Why do you want to do exception handling? Detailed Java exception handling mechanism

Source: Internet
Author: User
Tags arithmetic finally block garbage collection getmessage throwable
1. Background Introduction

Why do you want to do exception handling?

For a computer program, no one can guarantee that it will run without error, the main source of error is the following:

    • Code Error

    • User illegal input

    • Device errors and physical limitations: Full disk, memory overflow, hardware problem, network outage ...

Program error, then how to solve it? In the Java language, it provides exception handling mechanisms to help us deal with this problem.

The exception mechanism can leave the exception handling code and normal business code in the program, ensure the program code is more elegant, and can improve the robustness of the program.

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

The Try keyword immediately follows a block of code enclosed in curly braces (the curly braces must not be omitted), called the Try block, which puts code that might throw an exception, and a catch that corresponds to the exception type and a block of code that indicates that the catch block is used to handle this type of code block Multiple catch blocks can also be followed by a finally block, finally block is used to reclaim the physical resources opened in the try block, the exception mechanism will ensure that the finally block is always executed; the throws keyword is primarily used in method signatures to declare exceptions that the method might throw Throw is used to throw an actual exception, and throw can be used as a statement, throwing a specific exception object.

A simple example is as follows

The try {   //args represents the passed-in parameter, Args[0] represents the first parameter passed in, and Args[1] represents the passed-in second parameter   int a = Integer.parseint (Args[0]);   int b = Integer.parseint (args[1]);   int c = A/b;   SYSTEM.OUT.PRINTLN ("The result of dividing the two numbers you entered is:" +c);} catch (Indexoutofboundsexception IE) {   System.out.println ("Array out of bounds: insufficient number of arguments entered when running the program");} catch (NumberFormatException NE) {   System.out.println ("Number format exception: program can only receive integer parameters")} catch (ArithmeticException ae) {   //except 0 exception   System.out.println ("arithmetic exception");} catch (Exception e) {   System.out.println ("Unknown Exception");}

2. Knowledge Analysis

2.1 Exception handling mechanism

2.1.1 Using Try...catch to catch exceptions


Business Implementation Code

} catch (Exception e) {

Exception handling code


Execution process (or logic):

If the code in the try block runs smoothly, it is "all right"; If an exception occurs while executing the business logic code in the try block, an exception object is automatically generated that is referred to the Java Runtime Environment, which is called a throw (throw) exception. When the Java Runtime environment receives an exception object, it looks for a catch block that can handle the exception object, and if a suitable catch block is found, the exception object is handled by the catch block, a process known as catch (Catch) exception If the Java Runtime Environment cannot find a catch block to catch the exception, the runtime environment terminates and the Java program exits.

Note: Regardless of whether the program code block is in the try block or even the code in the Catch block, an exception is generated automatically whenever an exception occurs when the code block is executed. If the program does not define any catch blocks for this code, the Java Runtime Environment cannot find a catch block to handle the exception, and the program exits.

Inheritance system of 2.1.2 Anomaly class

When the Java Runtime environment receives an exception object, it determines once whether the exception object is an instance of the exception class or its subclasses after the catch block, and if so, the Java runtime environment calls the catch block to handle the exception, or the exception class in the next catch block is compared again.

Java Exception capture Process

As you can see, there can be multiple catch blocks behind a try block in order to provide different exception handling for different exception classes. When different unexpected situations occur on the system, different exception objects are generated, and the Java runtime determines which catch block to use to handle the exception, based on the exception class to which the exception object belongs.

In general, if a try block is executed once, only one catch block is executed after the try block, and it is never possible for more than one catch block to be executed. Unless you use continue in a loop to start the next loop, the next loop again runs the try block, which can cause multiple catch blocks to be executed.

Inheritance relationships between Java common exception classes

Java divides all non-normal situations into two types: exceptions and errors, all of which inherit the Throwable parent class.

Error errors, which generally refer to virtual machine-related problems such as system crashes, virtual machine errors, dynamic link failures, resource exhaustion, and so on, which can be unrecoverable or impossible to capture, causing an application outage. The application cannot normally handle these errors, so the application should not attempt to catch the Error object using a catch block, or declare that it might throw an error and any of its child class objects.

Common exceptions:

Indexoutofboundsexception: Array out-of-bounds exception due to insufficient number of arguments entered when running the program

NumberFormatException: Numeric format exception because the parameter entered when the program was run is not a number, but a letter

ArithmeticException: Except for 0 exceptions

Exception: When an unknown exception occurs, the exception object is always an instance of the Exception class or its subclasses, and the exception can be handled by Exception corresponding CATCH block

NullPointerException: null pointer exception that is thrown when attempting to invoke an instance or instance variable of a null object

Note: Not only should the catch block corresponding to the exception class be placed at the end of the exception capture, but all the catch blocks of the parent exception should be followed by the subclass exception catch block, that is, capturing the small exception before capturing the large exception, or a compilation error will occur. (If the parent class is before, the catch block of the child class that follows it will never get the chance to execute, because retrieving the catch block is performed from top to bottom)

2.1.3 Java7 provides multiple exception captures

Before Java7, each catch block can catch only one type of exception, but starting with Java7, a catch block can catch multiple types of exceptions.

There are two places to note when capturing multiple types of exceptions using a catch block:

    • When capturing multiple types of exceptions, multiple exception types are used | Separated.

    • When capturing multiple types of exceptions, the exception variable has an implicit final decoration, so the program cannot reassign the exception variable.

try {         int a = Integer.parseint (Args[0]);         int b = Integer.parseint (args[1]);         int c = A/b;         SYSTEM.OUT.PRINTLN ("The result of dividing the two numbers you entered is:" +c);      } catch (indexoutofboundsexception| numberformatexception| ArithmeticException e) {         System.out.println ("The program has an array out of bounds, a numeric format exception, one of the arithmetic exceptions");                  When capturing multiple exceptions, the exception variable defaults to final decoration         //So the following code compiles an error//        e = new ArithmeticException ("text");      } catch (Exception e) {         SYSTEM.OUT.PRINTLN ("Unknown Error");                  When capturing a type of exception, the exception variable does not have a final decoration         //All of the following code is completely correct         e = new RuntimeException ("test");      }

2.1.4 Access exception information

If the program needs to access information about the exception object in the catch block, it can be obtained by accessing the exception parameter in parentheses after the catch. When the Java runtime decides to call a catch block to process the exception object, it assigns the exception object to the exception parameter after the catch block, which the program can use to get information about the exception.

All of the exception objects contain the following common methods:

    • GetMessage (): Returns the detailed description string for the exception.

    • Printstacktrace (): Outputs the trace stack information for this exception to the standard error stream.

    • Printstacktrace (PrintStream s): Outputs the trace stack information for this exception to the specified output stream.

    • Getstacktrace (): Returns the trace stack information for this exception.

2.1.5 Using finally

Sometimes, the program opens some physical resources (such as database connections, network connections, and disk files) in a try block, and these physical resources must show recycling.

Note: Java's garbage collection mechanism does not reclaim any physical resources, and the garbage collection mechanism can only reclaim memory occupied by objects in heap memory.

To ensure that the physical resources opened in the try block can be reclaimed, the exception handling mechanism provides a finally block. The finally block is always executed, regardless of whether the code in the try block is an exception or not, regardless of which catch block is executed, even if a return statement is executed in a try block or catch block.

Complete syntax structure for Java exception handling:


Business Implementation Code

} catch (Exception1 e) {

Exception handling Block 1

} catch (Exception2 e) {

Exception handling Block 2

} finally {

Resource Reclaim block


Only the try block is required in the exception-handling syntax structure, and if there is no try block, there is no subsequent catch block and finally block, and the catch and finally blocks are optional, but the catch block and finally block appear at least one of them, and can also occur at the same time , you can have multiple catch blocks, the catch block that captures the parent exception must be behind the catch subclass exception, but not only the try block, no catch block, and finally block, and multiple catch blocks must be located after the try block. Finally blocks must be behind all catch blocks.

Note: Unless you call a method that exits a virtual machine in a try block or catch block, the finally block of exception handling will always be executed regardless of what code is executed in the try block, catch block, and what happens.

In general, try to avoid statements that result in methods terminating in a finally block, such as return or throw, or some strange situation may occur.

2.1.6 Nesting of exception handling

The case in a try block, catch block, or finally block that contains the complete exception-handling process is known as nesting of exception handling.

Exception-handling process code can be placed anywhere executable code can be placed, so the complete exception handling process can be placed in the try block, can also be placed in the catch block, can also be placed in the finally block.

There is no obvious limit to the depth of exception-handling nesting, but there is usually no need to use more than two layers of nested exception handling, too deep one is not necessary, but causes the program to be less readable.

2.1.7 Java7 A try statement for an auto-shutdown resource

Java7 enhances the function of the try statement, which allows for a pair of parentheses immediately after the Try keyword, which declares and initializes one or more resources, where the resources are those that must be shown closed at the end of the program (such as database connections, network connections, and so on). The try statement automatically shuts down these resources at the end of the statement.

Note: In order to ensure that the try statement can gracefully close the resource, these resource implementation classes must implement the Autocloseable or Closeable interface, and the close () method must be implemented to implement both interfaces. (Closeable is a sub-interface of autocloseable; the close () method declaration in the Closeable interface throws a IOException, so its implementation class can only declare a throw ioexception or its subclasses when implementing the Close () method The close () method declaration in the Autocloseable interface throws a exception, so its implementation class can declare any exception when implementing the Close () method

A try statement that automatically shuts down a resource is equivalent to containing an implicit finally block (the finally block is used to close the resource), so the try statement can have neither a catch block nor a finally block. You can also have multiple catch blocks and a finally block after you close the resource's try statement automatically if the program requires it.

Java7 almost all of the "resource Classes" (including various classes of file IO, JDBC programming connection, statement and other interfaces) have been rewritten, the rewritten resource classes have implemented the Autocloseable or closeable interface.

2.2 Checked anomaly and runtime anomaly system

Java exceptions are divided into two main categories: checked exceptions and runtime exceptions (runtime exceptions, some also called unchecked exceptions). All instances of the RuntimeException class and its subclasses are called Runtime exceptions, and exception instances that are not runtimeexception classes and their subclasses are referred to as checked exceptions. (When using to distinguish what type of exception, just look at the declared exception class is what you know)

Only the Java language provides checked exceptions, and no other languages provide checked exceptions. Java considers checked exceptions to be handled (fixed) exceptions, so Java programs must show handling checked exceptions, and if the program does not handle checked exceptions, the program will compile with errors that cannot be compiled.

There are two ways to handle checked exceptions:

    • The current method explicitly knows how to handle the exception, and the program should use the Try...catch block to catch the exception, and then fix the exception in the corresponding catch block.

    • The current method does not know how to handle this exception, and the exception should be declared when the method is defined.

Runtime exception is more flexible, runtime exception does not need to display the declaration throws, if the program needs to catch runtime exception, can also use Try...catch block to implement.

Note: Java Core technology

In the exception hierarchy, there are two branches: one branch is derived from RuntimeException, and another branch contains other exceptions. The rules for dividing these two branches are: exceptions caused by program errors belong to RuntimeException, and the program itself is not a problem, but exceptions due to problems such as I/O errors are other exceptions.

All exceptions to the Java language specification that are sent to the error class or the RuntimeException class are called not (not affected). Check for exceptions (unchecked), all other exceptions are called checked exceptions (checked). (during compilation, the compiler checks to see if an exception handler is provided for all checked exceptions)??????????? Pending discussion

2.3 Throwing exceptions using throws

The idea of throwing an exception using the throws declaration is that the current method does not know how to handle this type of exception, which should be handled by the caller at the top level, and 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 that will be passed to the JVM for processing. The JVM handles exceptions by printing abnormal tracking stack information and aborting the program, which is why our program automatically ends when it encounters an exception.

Throws declarations are thrown only in method signatures, throws can declare multiple exception classes, separating multiple exception classes with commas.

Once an exception is thrown using the throws statement declaration, you do not need to use the Try...catch block to catch the exception.

There is a restriction when using the throws declaration to throw an exception, that is, a rule in "two" when the method overrides: The subclass method declaration throws an exception type that is the subclass of the exception type thrown by the parent class method declaration, or the same exception that is thrown by the subclass method declaration that does not allow more exceptions than the parent class method declaration. (That is, the upper limit is set)

There are at least two major inconveniences to using the checked exception:

    • For checked exceptions in the program, Java requires that the exception be captured and handled, or that the exception is thrown by the display declaration, which increases the complexity of the programming.

    • If the declaration throws a checked exception in the method, it will cause the method signature to be coupled with the exception, and if the method is to override the parent class, the exception thrown by the method will also be limited by the exception thrown by the overridden method.

It is recommended to use runtime exceptions most of the time, instead of using checked exceptions, especially when the program needs to throw an exception on its own, and the runtime exception will be more concise.

When using the runtime exception, the program does not need to declare the throw checked exception in the method, and once a custom error occurs, the program simply throws the runtime exception. In the case of runtime exceptions, the Java compiler does not require exception capture processing or claims to be thrown, which is the programmer's discretion.

Using runtime exception is easy, but checked exception also has its advantages, checked exception can be at compile time to remind the programmer code may exist problems, remind the programmer must pay attention to handle the exception, or declare the exception has method of caller to handle, This prevents the programmer from forgetting to handle the exception because of carelessness.

2.4 Throwing Exceptions with throw

The system automatically throws an exception when the program is in error, and in addition, Java allows the program to throw exceptions by itself, and throws the exception using the throw statement.

2.5 Custom Exception Classes

User-defined exceptions should inherit the exception base class, and if you want to customize the runtime exception, you should inherit the RuntimeException base class. When defining an exception class, you typically need to provide two constructors: one is a parameterless constructor, and the other is a constructor with a string argument that acts as a description of the exception object (that is, the return value of the GetMessage () method of the exception object).

Package auctionexception;//The custom exception inherits the exception base class, and if you want to customize the runtime exception, you should inherit the RuntimeException base class. The custom exception class needs to provide two constructors: one is a parameterless constructor, the other is a constructor with a string argument, and this string acts as a description of//The exception object (that is, the return value of the GetMessage () method of the exception object) public class Auctionexception extends exception{      //1, parameterless constructor public   auctionexception () {   }   //2, constructor with one string argument Public   auctionexception (String msg) {      //constructor      Super (msg) to call the parent class via super;}   }

2.6 Catch and throw are used simultaneously

In practice, when an exception occurs, a method alone cannot handle the exception completely, and several methods must be collaborated to fully handle the exception. That is, in the current method in which the exception occurs, the program only partially handles the exception, and some processing needs to be done in the caller of the method, so the exception should be thrown again so that the caller of the method can catch the exception.

In order to achieve this situation in which multiple methods work together to handle the same exception, you can combine the throw statement in the catch block.

The use of this catch and throw combination is very common in large enterprise applications, where the processing of exceptions is usually divided into two parts: one is that the background needs to log the details of the occurrence of the exception, and the application needs to communicate some kind of hint to the application user based on the exception.

Package Catchandthrow;import Auctionexception.auctionexception;public class Catchandthrow {private Double Initprice      = 30.0; Because the auctionexception exception is thrown in the method, a declaration is required here to throw auctionexception exception public void bid (String bidprice) throws Auctionexcept      ion{double d = 0.0;      try {d = double.parsedouble (Bidprice);                   } catch (Exception e) {///here to complete the repair process that can be performed on the exception in this method//Here is just the tracking stack information for the console printing exception e.printstacktrace ();      Throw the custom exception again throw new Auctionexception ("Bid price must be numeric, cannot contain other characters");      } if (Initprice > D) {throw new Auctionexception ("Bid price is lower than bid price, no auction is allowed");   } initprice = D;      } public static void Main (string[] args) {Catchandthrow catchandthrow = new Catchandthrow ();      try{catchandthrow.bid ("DF"); } catch (Auctionexception ae) {//captures the exception in the bid () method again and processes the exception, where the detailed description of the exception is output to the standard error (ERR) output System.err.printl      N (ae.getmessage ()); }   }}

2.7 Exception Tracking Stack

The Printstacktrace () method of the exception object is used to print the trace stack information of the exception, and according to the output of the Printstacktrace () method, the developer can find the source of the exception and track the process of triggering the exception.

3. Frequently Asked Questions

3.1 Why can't I access the variables declared in the try block in the finally block?

A: A variable declared in a try block is a local variable within a block of code that is valid only within a try block and cannot be accessed in the catch block and finally block.

3.2 Why is it best not to use the catch all statement?

A: The so-called catch all statement refers to an exception capture module that can handle all possible exceptions that occur to a program. For example, using the exception or Throwable class to catch all exceptions, although this is a way to handle exceptions, it does not accurately describe the cause of the exception, and it is difficult for us to accurately troubleshoot it.

3.3 Is there any exception handling for annotation methods?

A: Some, such as spring has annotation-based global exception handling (using @exceptionhandler)

4. Reference documents

From the third edition of "Crazy Java Handout", the code imitates the example of the book.

Today's share is here, I hope that you can correct me, learn from each other ~

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.