Briefly describe Java exception handling

Java exception handling

One, the concept
of exception 1, exception (exception) is an exception that occurs in the code sequence during operation.
2. Hierarchy of Exception Class
All exception classes are subclasses inherited from java.lang.Exception class.
The Exception class is a subclass of the Throwable class. In addition to the Exception class, Throwable also has a subclass Error.
Java programs usually do not catch errors. Errors generally occur when serious failures occur, and they are outside the scope of the Java program.
Error is used to indicate an error occurred in the runtime environment.
The exception class has two main subclasses: IOException class and RuntimeException class.
Two, common exception types
Insert picture description here
Three, exception handling
Java exception handling is controlled by 5 keywords: try, catch, throw, throws and finally.
1. Try-catch structure
try{ code A code B }catch (ExceptionType e) { exception handling code C } code D expectation: A—>B—>C—>D when the program has no exceptions. Actually: A—>Exception handling— >C—>D code B is abnormal Actually: A—>B—>Exception handling—>C—>D code B is abnormal 2, finally keyword










Sometimes, some physical resources are referenced in the try block, such as database connections, network connections, or disk files. Once an exception occurs in the try block, these resources cannot be guaranteed to be released. There
must be a very precise way to ensure that the resources are certain Get released, regardless of whether there is an exception, which is why finally exists.
ry{ code A code B }catch (ExceptionType e) { exception handling code C }finally { recycling code resource code D } code E







Note the following:
catch cannot exist independently of try.
It is not mandatory to add a finally block after try/catch.
There cannot be neither a catch block nor a finally block after the try code.
No code can be added between try, catch, and finally blocks.

Code display:

package exception;

public class ArithmeticException {
    
    
    public static void main(String[] args) {
    
    

        //算数错误
        try {
    
    
            int num=5/0;                          //出现异常
            System.out.println(num);              // 异常后的程序不再执行
        }catch (java.lang.ArithmeticException e){
    
      //捕捉异常
            System.out.println("除数不能为零");     //处理异常
        }finally {
    
    
            System.out.println("资源回收");        //资源回收
        }
        System.out.println("helloworld");         //后面的程序继续执行

        //试图访问null对象引用
        try {
    
    
            String  str = null;                  //定义一个空的字符串
            System.out.println(str.length());    //输出空字符串长度,出现异常
        }catch (NullPointerException c){
    
             //捕捉异常
            c.printStackTrace();                 //打印异常
            System.out.println("不能为空");       //处理异常
        }finally {
    
    
            System.out.println("回收资源");       //回收资源
        }
        System.out.println("程序继续执行");        //后面的程序继续执行
    }
}

Running results:
Insert picture description here
3, multiple catch blocks

try{ code A try { code A1 code B1 code C1 }catch (ExceptionType2 e2) { exception handling code D2 } code C }catch (ExceptionType2 e2) { exception handling code D1 }finally{ recycling resource code E } code F














The above code snippet contains 3 catch blocks.
You can add any number of catch blocks after the try statement.
If an exception occurs in the protection code, the exception is thrown to the first catch block.
If the data type of the thrown exception matches ExceptionType1, it will be caught here.
If it does not match, it will be passed to the second catch block.
So, until the exception is caught or through all catch blocks.

Code display:

package exception;

import java.lang.ArithmeticException;

public class MultiplAanomalies {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            int i=5/1;           //语句正确,正常执行
            System.out.println(i);
            try {
    
    
                int num = 5/0;                //出现异常
                System.out.println(num);      //异常语句后面的代码不再执行 
                String str = null;           
                System.out.println(str.length());
            }catch (ArithmeticException c){
    
            //捕捉异常     
                System.out.println("出现异常啦");
            }catch (NullPointerException c){
    
             
                System.out.println("出现异常");
            }
        }catch (Exception c){
    
    
            System.out.println("出现异常了");
        }finally {
    
    
            System.out.println("资源回收");
        }
        System.out.println("程序继续执行");
    }
}

Running results:
Insert picture description here
3. Throw and throws keywords
(1), throw keyword
Sometimes an exception needs to be explicitly raised. The Java language can explicitly raise an exception with the throw statement.
Once the execution flow encounters a throw statement, it will stop immediately, and the next statement will not be executed.
Simply put, it is to customize an exception
(2). The throws keyword
throws follows the method, indicating that the method may throw some or some exceptions, and this method does not care or is inconvenient to handle, and it is called by the method To handle these exceptions.

Code display:

package Throw;

//自定义异常类,继承Exception类
public class MyExcertion extends Exception{
    
    

    public MyExcertion(){
    
          //无参构造方法
        super();
    }


    public MyExcertion(String a){
    
          //有参构造方法
        super(a);
    }
}


package Throw;

public class Test1 {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            show();
        } catch (MyExcertion myExcertion) {
    
    
            myExcertion.printStackTrace();  //打印异常
            System.out.println("出现异常");
        }
    }


    public static void show() throws MyExcertion{
    
    
        if (2>1){
    
                               //自定义异常,比如去银行取钱,取款金额大于卡内余额则会显示余额不足(相当于出现异常)。
            throw new MyExcertion();
        }
    }
}

Operation results:
Insert picture description here
Fourth, exception usage rules
Do not set try and catch for every statement that may be abnormal. Although the use of exceptions can separate conventional code and error handling code, thereby improving the readability of the code, improper use of exceptions will reduce the readability of the code.
Avoid always catching Exception or Throwable, but catch the specific exception class. This can make the program clearer.
Under what circumstances are exceptions used? If the method encounters an abnormal condition that it does not know how to handle, then it should throw an exception.
Don't use try...catch in the loop, try to put try...catch outside the loop or avoid using it.
Exception handling should not be used to control the normal flow of the program. Do not regard exceptions as "super if

Guess you like

Origin blog.csdn.net/tan1024/article/details/110229201