[Java notes] exception handling

  The default handling scheme of the java virtual machine will end the program when an exception occurs in the program, and an exception in a certain part of the actual project should not affect the execution of the subsequent program, so you must handle the exception yourself.

1. Java exception class

1. The difference between compile-time exception and runtime exception

Insert picture description here

2. Throwable member methods

  Member method of abnormal ancestor class Throwable
Insert picture description here

public class ThrowableTest {
    
    
    public static void main(String[] args) {
    
    
        System.out.println("开始");
        method();
        System.out.println("结束");
    }

    private static void method() {
    
    
        try {
    
    
            int a[]={
    
    1,2};
            System.out.println(a[3]);
        }catch (ArrayIndexOutOfBoundsException e){
    
    
//            System.out.println(e.getMessage());//3
//            System.out.println(e.toString());//java.lang.ArrayIndexOutOfBoundsException: 3
            e.printStackTrace();
            /*
                java.lang.ArrayIndexOutOfBoundsException: 3
                at _3Exception.ThrowableTest.method(ThrowableTest.java:25)
                at _3Exception.ThrowableTest.main(ThrowableTest.java:18)
            */
        }
    }
}

2. Handling exceptions

  If there is a problem with the program, we need to deal with it ourselves. There are two solutions:

  • try…catch
  • throws

1. Try...catch of exception handling

format:

try{
    
    
	可能出现异常的代码;
}catch(异常类名 变量名){
    
    
	异常处理代码;
}finally{
    
    
	必须执行的代码;
}

Insert picture description here

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

        try {
    
    
            int a[]={
    
    1,2};
            System.out.println(a[2]);
        }catch (ArrayIndexOutOfBoundsException e){
    
    
            System.out.println("越界");
            e.printStackTrace();
        }
        System.out.println("结束");
    }
}

Insert picture description here


2. Throws of exception handling

  Although we can handle exceptions through try...catch..., we don't have the authority to handle exceptions in all cases. That is to say, sometimes we can't handle the exceptions that may occur. What should we do at this time?
  In response to this situation, java provides throws solutions

public class ThrowsTest {
    
    
    public static void main(String[] args) {
    
    
        System.out.println("开始");
        
        method1();//运行时异常如果需要程序继续执行还需要try catch
        
        try {
    
    
            method2();
        } catch (ParseException e) {
    
    
            e.printStackTrace();
        }
        System.out.println("结束");
    }

    //运行时异常
    public static void method1() throws ArrayIndexOutOfBoundsException{
    
    
        int a[] = {
    
    1, 2};
        System.out.println(a[2]);
    }

    //编译时异常
    public static void method2() throws ParseException {
    
    
        String s="2048-08-01";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date d=sdf.parse(s);//此处有编译异常
        System.out.println(d);
    }
}
  • Note that
    Insert picture description here
    there is no substantive processing of throwing exceptions. The real processing is still to try and catch processing.

Three. Custom exception

1. Steps

  1. Customize a custom exception class, you must inherit the Exception class
  2. Use throws to declare the exception in the method header where an exception may occur
  3. Use throw to throw the custom exception object where an exception occurs in the method body

2. Use of throws and throw

  Java provides a throws processing solution. In which function the statement that may cause an exception appears, the exception must be declared through throws in the function header of the function, and the exception will be thrown through throw in the case of a problem.
format:

返回值类型 方法名称 throws 异常类名{
    
    
	if(发生异常)
		throw 异常类对象;
}

3. The difference between throws and throw

Insert picture description here

4. Case

  • Custom exception class
    Call the constructor of the parent class Exception through super
//异常类,固定格式
public class ScoreException extends Exception {
    
    //继承Exception类,编译异常
    ScoreException(){
    
    }

    ScoreException(String message){
    
    
        super(message);//传给祖先类
    }
}
  • Possible abnormalities
//会产生异常的地方
public class Teacher {
    
    
    public static void checkScore(int score) throws ScoreException {
    
    
        if (score <0 ||score>100){
    
    
            throw new ScoreException(score+":成绩不符合规范");//抛出异常对象
        }else {
    
    
            System.out.println("成绩符合规范");
        }
    }
}
  • test
//测试
public class TeacherTest {
    
    
    public static void main(String[] args) {
    
    
        Scanner in = new Scanner(System.in);
        System.out.println("输入分数:");
        int s=in.nextInt();

        Teacher t = new Teacher();
        try {
    
    
            t.checkScore(s);//编译异常,需要用try catch抓起来
        } catch (ScoreException e) {
    
    
            e.printStackTrace();
        }
    }
}

Guess you like

Origin blog.csdn.net/Supreme7/article/details/107069740