Java exception handling study notes (Exception and Error)

What is an exception?
    Just like us, everyone wants to be healthy, but life does not follow what we think. There will always be conditions such as fever and cough. The program is also the same, and various abnormal conditions may occur during the program's operation.
    Divide by zero exception example:

public class Demo {
    
    
    public static void main(String[] args) {
    
    
        //传入两个参数
        int result = DivideByZero(4, 0);
        System.out.println(result);
    }
    //定义一个两个数相除的方法
    public static int DivideByZero(int a, int b){
    
    
        return a/b;
    }
}

The operation result will report a division by zero exception: Insert picture description here
    java.lang.ArithmeticException appears in the operation result of the above example. This exception is only one of the Java exception classes. The picture below is taken from the Internet:
Insert picture description here
    As can be seen from the picture above, there are two Throwables. Directly subclass Error and Exception classes. Error represents an error in the program, and Exception represents an exception generated in the program.

  • The Error class is called an error class: it represents an internal system error or resource exhaustion error generated by Java at runtime. This is more serious and cannot be repaired only by modifying the program.
  • The Exception class is called the exception class: it represents the errors that Cheng Xun can handle. There is a RuntimeException class in the Exception class. This class and its subclasses represent runtime exceptions. All other classes under the Exception class represent compile-time exceptions.

Exception handling try...catch...finally
    try... cathc is a special method provided by Java for handling exceptions. The syntax is as follows:

try{
    
    
   //代码逻辑
 }catch(ExceptionType e){
    
    
   //对ExceptionType的异常处理
}

Let's transform the above example:

public class Demo {
    
    
    public static void main(String[] args){
    
    
        try {
    
    
            //传入两个参数
            int result = DivideByZero(4, 0);
            System.out.println(result);
        }catch (Exception e){
    
    
            System.out.println("程序发生了异常...");
        }
        System.out.println("程序继续向下执行...");
    }
    //定义一个两个数相除的方法
    public static int DivideByZero(int a, int b){
    
    
        return a/b;
    }
}

Running result: Insert picture description here
    It is worth noting that in the try code block, the code after the statement where the exception occurs will not be executed. Sometimes we write programs just to hope that some code must be executed regardless of whether it occurs or not. We can add a finally code block after the try...catch statement.
format:

try{
    
    
     //try块中放可能发生异常的代码。     
     //如果执行完try且不发生异常,则接着去执行finally块和finally后面的代码(如果有的话)。     
     //如果发生异常,则尝试去匹配catch块。

}catch(SQLException SQLexception){
    
    
    //每一个catch块用于捕获并处理一个特定的异常,或者这异常类型的子类。Java7中可以将多个异常声明在一个catch中。
    //catch后面的括号定义了异常类型和异常参数。如果异常与之匹配且是最先匹配到的,则虚拟机将使用这个catch块来处理异常。
    //在catch块中可以使用这个块的异常参数来获取异常的相关信息。异常参数是这个catch块中的局部变量,其它块不能访问。
    //如果当前try块中发生的异常在后续的所有catch中都没捕获到,则先去执行finally,然后到这个函数的外部caller中去匹配异常处理器。    
    //如果try中没有发生异常,则所有的catch块将被忽略。
}catch(Exception exception){
    
    
    //...
}finally{
    
    
   //finally块通常是可选的。   
   //无论异常是否发生,异常是否匹配被处理,finally都会执行。
   //一个try至少要有一个catch块,否则, 至少要有1个finally块。但是finally不是用来处理异常的,finally不会捕获异常。
  //finally主要做一些清理工作,如流的关闭,数据库连接的关闭等。 
}

Examples:

public class Demo {
    
    
    public static void main(String[] args){
    
    
        int result = 0;
        try {
    
    
            //传入两个参数
            result = DivideByZero(4, 0);
            System.out.println(result);
        }catch (Exception e){
    
     //对异常进行处理
            System.out.println("程序发生了异常...");
        }finally {
    
     //finally代码块
            System.out.println("finally代码块执行了...");
            System.out.println("输出结果:" + result);
        }
        System.out.println("程序继续向下执行...");
    }
    //定义一个两个数相除的方法
    public static int DivideByZero(int a, int b){
    
    
        return a/b;
    }
}

Running result: Insert picture description here
throws keyword:
    throws keyword is used to declare that a method may have an exception, so that the caller must handle the exception in the program. The syntax format is as follows:

//修饰符 返回值 方法名(参数1,参数2) throws ExceptionType1,ExceptionType2{}
//可以抛出多个异常。
public class Demo {
    
    
    public static void main(String[] args){
    
    
        DivideByZero(2,0);//调用者不处理该异常就会编译报错
    }
    //定义一个两个数相除的方法,该方法抛出一个异常
    public static int DivideByZero(int a, int b) throws Exception{
    
    
        return a/b;
    }
}

Custom exceptions:
    Sometimes it is possible to describe unique situations in the program during program development. This requires our programmers to customize exceptions, but custom exceptions must be inherited from Exception or subclasses. In actual development, the exception handling class will have status code, exception information, etc.
Syntax format:

  //throw Exception 异常对象
  //thorw关键字用于在方法中声明抛出异常的实例对象

Examples:

//自定义异常处理类
public class DivideByZeroMin extends Exception {
    
    
    public DivideByZeroMin(){
    
    
        super();//调用Exception的无参构造方法
    }
    public DivideByZeroMin(String msg){
    
    
        super(msg);调用Exception的有参构造方法
    }
}
//测试类
public class Demo {
    
    
    public static void main(String[] args){
    
    
        try {
    
    
            int i = DivideByZero(4, -2);
        } catch (DivideByZeroMin e) {
    
    
            e.printStackTrace();
        }
    }
    //定义一个两个数相除的方法,该方法抛出一个自定义异常
    public static int DivideByZero(int a, int b) throws DivideByZeroMin{
    
    
        if ( b < 0){
    
    
            //使用throw关键字声明异常对象
            throw new DivideByZeroMin("被除数不能是负数");
        }
        return a/b;
    }
}

Operation result:
Insert picture description here
Come on! ! !

Guess you like

Origin blog.csdn.net/qq_42494654/article/details/109342976