Java se note exception mechanism

Java exception mechanism

In an ideal situation, our program will run according to our ideas. It is reasonable that there will be no problems. However, the code is not necessarily perfect after actual writing. There may be situations we have not considered. If these situations can get an error result normally, it is OK, but what if they directly lead to problems in program operation?

public static void main(String[] args) {
    test(1, 0);   //When b is 0, can it work normally?

private static int test(int a, int b){
    return a/b;   //There is no judgment, but direct calculation

Exception in thread "main" java.lang.ArithmeticException: / by zero
	at com.test.Application.test(
	at com.test.Application.main(

When the program runs without consideration, there may be exceptions or errors!


In fact, we have been exposed to some exceptions before, such as array out of bounds exceptions, null pointer exceptions, arithmetic exceptions, etc. they are all Exception types. Each of our exceptions is also a class, and they all inherit from the Exception class! The Exception type is still an object of class in nature, but the Exception type supports throwing when there is a problem in the program operation (that is, the red error message above) and can also be declared in advance to inform the user that it is necessary to deal with possible exceptions!

Runtime exception

The first type of exception is run-time exception, such as the above columns. You can't know whether there will be a problem in the code at the compilation stage. You can only know whether there will be an error at run time (normally, there will be no error). Such an exception is called run-time exception. All runtime exceptions are inherited from RuntimeException.

Compile time exception

Another type of Exception is compile time Exception. Compile time Exception is an explicit Exception that will occur. Exceptions that need to be handled in the compilation stage (Exception capture) will not pass compilation if they are not handled! By default, exceptions inherited from the Exception class are compile time exceptions.

File file = new File("my.txt");
file.createNewFile();   //To call this method, you first need to handle the exception


Errors are more serious than exceptions. Exceptions are unusual, but they do not necessarily lead to fatal problems. Errors are fatal. In general, errors may prevent the JVM from continuing to operate normally. For example, OutOfMemoryError is a memory overflow error (the memory occupation has exceeded the limit, and it is impossible to continue to apply for memory)

int[] arr = new int[Integer.MAX_VALUE];   //Can you create such a large array?

After running, the following contents are obtained:

Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
	at com.test.Main.main(

Errors are inherited from the error class. Generally, the program can only handle exceptions. Errors are difficult to handle. Error and exection are inherited from the Throwable class. When an error or exception occurs in the program and is not handled, the program (current thread) will terminate:

int[] arr = new int[Integer.MAX_VALUE];
System.out.println("lbwnb");  //Can you print normally?

Exception handling

When an exception occurs when the program does not run as we want (it will be handled by the JVM by default. If the JVM finds any exception, it will immediately terminate the program and print the stack tracking information on the console), we want to handle the problem ourselves and let the program continue to run. We need to catch the exception, such as:

int[] arr = new int[5];
arr[5] = 1;  //We need to deal with this situation to ensure that the following code runs normally!

We can use try and catch statement blocks to handle:

int[] arr = new int[5];
try{    //Running code in a try block
     arr[5] = 1;    //When an exception occurs in the code, the exception will be caught and an object of exception type will be obtained in the catch block
}catch (ArrayIndexOutOfBoundsException e){   //Exception type caught
     System.out.println("The program runs abnormally!");  //Execute in case of exception
//The following code will work normally

After the exception is caught, it is handled by ourselves (no longer handed over to the JVM), so it will not cause the program to terminate.

We can print stack trace information by using e.printStackTrace() to locate the location of our exception:

java.lang.ArrayIndexOutOfBoundsException: 5
	at com.test.Main.main(    //There is a problem with line 7 of the Main class
 The program runs abnormally!

Runtime exceptions may not be caught at compile time, but must be handled at compile time:

File file = new File("my.txt");try {  file.createNewFile();} catch (IOException e) {  //Catch declared exception type e.printStackTrace();}

Subclasses with more than Exception types can be captured, as long as they are classes inherited from Throwalbe, that is, errors can also be captured, but this is not recommended, because errors are generally problems related to virtual machines, and errors should be solved from the root of the problem.

Exception throw

When others call our method, if the wrong parameters are passed in, which makes the program unable to run normally, we need to manually throw an exception to terminate the program and continue to run, and inform the upper level of the problem in the execution of the method:

public static void main(String[] args) {        try {            test(1, 0);        } catch (Exception e) {   //Catch the exception that will appear in the method e.printstacktrace();}} Private static int test (int a, int b) throws exception {/ / declare the type of exception thrown if(b == 0) throw new Exception("0 cannot divide!"); / / create an exception object and throw an exception return a/b; / / throwing an exception will terminate the code}

Throw an exception through the throw keyword (after throwing an exception, the following code will no longer be executed). When the program runs to this line, the execution will be terminated and an exception will appear.

If a non runtime exception is thrown in the method, but you do not want to handle it in this method, but leave it to the caller to handle the exception, you need to explicitly declare the thrown exception type after the method definition! If a runtime exception is thrown, you do not need to declare the exception type behind the method, and you do not need to catch it when calling. However, an exception will also cause the program to terminate (if a runtime exception occurs and is not caught, it will be handed over to the JVM for processing by default, that is, directly abort the program and print stack tracking information on the console)

If you want to call a method that declares a compile time exception, but still don't want to handle it, you can declare throws on the method to continue to hand it over to the upper level for processing.

public static void main(String[] args) throws Exception {  //If an exception occurs, throw it up instead of processing test (1, 0) in this method;} Private static int test (int a, int b) throws exception {/ / declare the type of exception thrown if(b == 0) throw new Exception("0 cannot divide!"); / / create an exception object and throw an exception return a/b;}

When the main methods declare that they throw an exception, the JVM will handle the exception, that is, the default processing method (directly abort the program and print stack tracking information on the console)

Exceptions can only be caught once. When nested exceptions are caught, they will only be caught at the innermost layer:

public static void main(String[] args) throws Exception {        try{            test(1, 0);        }catch (Exception e){            System.out.println("Outer layer");        }    }    private static int test(int a, int b){        try{            if(b == 0) throw new Exception("0 You can't divide!");        }catch (Exception e){            System.out.println("Inner layer");            return 0;        }        return a/b;    }

Custom exception

The JDK has defined some exceptions for us in advance, but it may not be enough for us, so we need to customize the exceptions:

public class MyException extends Exception {  //Directly inherit} public static void main (string [] args) throw myexception {throw new myexception(); / / directly use}

You can also use the construction method with description of the parent class:

public class MyException extends Exception {    public MyException(String message){        super(message);    }}public static void main(String[] args) throws MyException {    throw new MyException("A custom error occurred");}

Catching the type specified by the exception will catch all its sub exception types:

try {  throw new MyException("A custom error occurred");} catch (Exception e) {    //Catch the parent exception type System.out.println("exception caught");}

Multiple exception capture and finally keyword

When multiple types of exceptions may occur in the code, we want to handle different types of exceptions in different situations, so we can use multiple exception capture:

try {  //....} catch (NullPointerException e) {            } catch (IndexOutOfBoundsException e){} catch (RuntimeException e){            }

Note that similar to the if else if structure, the parent exception type can only be placed last!

try {  //....} catch (RuntimeException e) {/ / if the parent type is first, the child class will also be caught} catch (NullPointerException e) {/ / it will never be caught} catch (IndexOutOfBoundsException e) {/ / it will never be caught}

If you want to handle these exceptions together:

try {     //....} catch (NullPointerException | IndexOutOfBoundsException e) {/ / just separate each type with}

When the program runs, we hope that the tasks that will be executed at the end, whether there are exceptions or not, can be handed over to the finally statement block:

try {    //....} catch (exception E) {} finally {system. Out. Println ("lbwnb"); / / whether an exception occurs or not, it will be executed at the end}

The try statement block must match at least one of catch or finally:

try {    int a = 10;    a /= 0;}finally {  //If exceptions are not caught, the program will terminate, but the following contents will still be executed in the end: System.out.println("lbwnb");}

Think: try, catch, and finally execute in the following order:

private static int test(int a){  try{    return a;  }catch (Exception e){    return 0;  }finally {    a =  a + 1;  }}

Tags: Java JavaSE

Posted on Wed, 20 Oct 2021 16:42:31 -0400 by public-image