ZJU-java advanced notes week 7 (exception handling)

  1. Definition of exception
    Insert picture description here

  2. Catch exception example

try{
    
    
    //可能产生异常的代码
}catch(Type1 id1){
    
    
    //处理Type1异常的代码
}catch(Type2 id2){
    
    
    //处理Type2异常的代码
}catch(Type3 id3){
    
    
    //处理Type3异常的代码
        }

The significance of exception capture: the program does not need to be terminated when an exception occurs
3.

  1. What can be done after the abnormal object is caught
  1. String getMessage();
  2. String toString();
  3. void printStackTrace();
public static void main(String[] args){
    
    

        try {
    
    
            k();
        }catch (ArrayIndexOutOfBoundsException e){
    
    
            System.out.println(e.getMessage());//放在异常对象里面的值
            System.out.println(e);//异常类的名字和它的message
            e.printStackTrace();//打印调用堆栈,显示调用关系及发生行号
        }
}

But it must not go back, and the specific processing logic depends on the needs of business logic

  1. Throwing exceptions
    Add throw e; (Imperative sentence, throw) in catch{}.
    Effect: as if not caught

  2. The exception statement is
    placed after the function that may throw an exception, as a statement, throws

    public static void readFile() throws OpenException{
    
    
        if(open() == -1){
    
    
            throw new OpenException();
        }
}
  1. What can be "thrown out"?
    Any object that inherits the Throwable class
    Exception class inherits Throwable

  2. Throwing subclass exceptions can be caught by the parent exception catcher
    Universal catcher-catch any exception

    catch(Exception e){
    
    
        System.out.println("Caught an exception");
}
  1. There can be no more exceptions in the subclass than the parent class,
    but the exceptions that the parent class constructor will throw must be in the subclass constructor

Guess you like

Origin blog.csdn.net/weixin_44997802/article/details/108572590