[JAVA exception handling | try-catch, throw, throws]

abnormal

General exception code:

public class Exception01 {
    
    
    public static void main(String[] args) {
    
    
        int n1 = 10;
        int n2 = 0;
        // n1 / n2 => 10 / 0
        int res = n1/n2;
        System.out.println("程序继续运行……");
    }
}

Exception capture (try-catch) is set:

public class Exception01 {
    
    
    public static void main(String[] args) {
    
    
        try{
    
    
            int n1 = 10;
            int n2 = 0;
            // n1 / n2 => 10 / 0
            int res = n1/n2;
        } catch (Exception e){
    
    
            // TODO:handle exception
            //e.printStackTrace();//打印异常堆栈,即将异常出错的代码和信息输出
            System.out.println("异常信息=" + e.getMessage());
        }
        System.out.println("程序继续运行……");
    }
}

Exception introduction

basic concept

In the Java language, abnormal situations that occur during program execution are called "abnormalities". ( Syntax errors and logic errors during development
are not exceptions )

Abnormal events can be divided into two categories (Error, Exception)

  1. Error (Error) : A serious problem that the Java virtual machine cannot solve. Such as: JVM system internal errors, resource exhaustion and other serious situations. For example: StackOverflow Error stack overflow] and ooM (out of
    memory), Error is a serious error, the program will crash.
  2. Exception : Other general problems caused by programming errors or accidental external factors can be handled with specific codes. For example, empty finger access, trying to read non-existent files, network connection
    interruption, etc., Exception is divided into two categories: runtime exception [exception that occurs when the program is running] and compile-time exception [compiler check exception].

Class diagram:

image-20211007080111311

Common runtime exceptions

  1. NullPointerException Null pointer exception

    String name = null;
    System.out.println(name.length());
    
  2. ArithmeticException math operation exception

    int n1 = 10;
    int n2 = 0;
    int res = n1/n2;
    
  3. ArrayIndexOutOfBoundsException Array subscript out of bounds exception

    int[] arr = {
          
          1, 2, 4};
    for (int i = 0; i <= arr.length; i++) {
          
          
        System.out.println(arr[i]);
    }
    
  4. ClassCastException type conversion exception

    public class ClassCastException_ {
          
          
        public static void main(String[] args) {
          
          
            A b = new B();//向上转型
            B b2 = (B)b;//向下转型,OK的
            C c2 = (C)b;//这里会抛出ClassCastException类型转换异常
        }
    }
    
    class A {
          
          }
    class B extends A {
          
          }
    class C extends B {
          
          }
    
  5. NumberFormatException number format is incorrect exception

    String name = "Jack";
    //将 String 解析成 int
    int num = Integer.parseInt(name);
    

Common compile-time exceptions

  1. SQLException
  2. IOException
  3. FileNotFoundException
  4. ClassNotFoundException
  5. EOFException
  6. IlldgalArgumentException

exception handling

basic introduction

Exception handling is the way an exception is handled when an exception occurs.

The way exceptions are handled

  1. try-catch-finally
    programmers catch exceptions in the code and handle them by themselves
  2. throws
    throws the exception that occurs and hands it over to the caller for processing. The top-level handler is the JVM

try-catch-finally

try{
    
    
    //代码/可能有异常
} catch (Exception e) {
    
    
    //捕获异常
    //1.当异常发生时
    //2.系统将异常封装成Exception对象e,,传递给catch
    //3.得到异常对象后,程序员自己处理
} finally {
    
    
    //没有finally语法也是可以通过的
    //不管有没有异常,finally一定要执行
}

throws

image-20211007083738808

Exceptions use throws by default.

try-finally

Directly using try-finally for cooperation is equivalent to not catching exceptions, so the program will crash directly. The application scenario is to execute a piece of code, regardless of whether an exception occurs, a certain business logic must be executed.

try{
    
    
    //代码......
} finally {
    
    
    //总是执行的代码
}

Try Mechanism

TryCatchDetail01.java

Use ctrl + alt + tshortcut keys to set try-catch

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-7aIbVacn-1644128312071)(.\image\image-20211007084308512.png)]

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

        try {
    
    
            String str = "Jack";
            int a = Integer.parseInt(str);
            System.out.println("数字:" + a);
        } catch (NumberFormatException e) {
    
    
            System.out.println("异常信息 = " + e.getMessage());
        }

        System.out.println("程序继续......");
    }
}

Use finally if you want a piece of code to be executed no matter what happens.

There can be multiple catch statements to capture different exceptions for different business processing), requiring parent exceptions to follow and subclass exceptions to precede, for example (Exception follows, NullPointerException precedes), if an exception occurs, only one will be matched catch.

TryCatchDetail02.java

public class TryCatchDetail02 {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            Person person = new Person();
            person = null;
            System.out.println(person.getName());//NullPointerException
            int n1 = 10;
            int n2 = 0;
            int res = n1 / n2;//ArithmeticException
        } catch (Exception e) {
    
    
            System.out.println(e.getMessage());
        } finally {
    
    
        }
    }
}

class Person{
    
    
    private String name;

    public String getName() {
    
    
        return name;
    }
}

Improved multiple exception handling:

Subclass exceptions must be placed first! ! !

public class TryCatchDetail02 {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            Person person = new Person();
            person = null;
            System.out.println(person.getName());//NullPointerException
            int n1 = 10;
            int n2 = 0;
            int res = n1 / n2;//ArithmeticException
        } catch (NullPointerException e) {
    
    
            System.out.println("空指针异常: " + e.getMessage());
        } catch (ArithmeticException e) {
    
    
            System.out.println("算数异常: " + e.getMessage());
        } catch (Exception e) {
    
    
            System.out.println("一般异常: " + e.getMessage());
        } finally {
    
    
        }
    }
}

class Person{
    
    
    private String name;

    public String getName() {
    
    
        return name;
    }
}

TryCatchDetail03.java

public class TryCatchDetail03 {
    
    
    public static void main(String[] args) {
    
    
        try{
    
    
            int n1 = 10;
            int n2 = 0;
            System.out.println(n1 / n2);
        } finally {
    
    
            System.out.println("执行了finally...");
        }

        //不会继续运行,程序运行完finally后直接崩溃
        System.out.println("程序继续运行...");
    }
}

TryCatchExercise01.java

public class TryCatchExercise01 {
    
    
    public static int method(){
    
    
        try{
    
    
            String[] names = new String[3];
            if(names[1].equals("tom")){
    
    //NullPointerException
                System.out.println(names[1]);
            } else{
    
    
                names[3] = "hspedu";
            }
            return 1;
            }
        catch (ArrayIndexOutOfBoundsException e){
    
    
            return 2;
        }
        catch (NullPointerException e){
    
    
            return 3;
        }
        //由于finally必须执行,则一定返回4
        finally{
    
    
            return 4;
        }
    }

    public static void main(String[] args) {
    
    
        System.out.println(method());
    }
}

TryCatchExercise02.java

public class TryCatchExercise02 {
    
    
    public static int method(){
    
    
        int i = 1;
        try{
    
    
            i++;//2
            String[] names = new String[3];
            if(names[1].equals("tom")){
    
    //NullPointerException
                System.out.println(names[1]);
            } else{
    
    
                names[3] = "hspedu";
            }
            return 1;
        }
        catch (ArrayIndexOutOfBoundsException e){
    
    
            return 2;
        }
        catch (NullPointerException e){
    
    
            return ++i;//3
        }
        //由于finally必须执行,则一定返回4
        finally{
    
    
            return ++i;//4
        }
    }

    public static void main(String[] args) {
    
    
        System.out.println(method());//4
    }
}

TryCatchExercise03.java

public class TryCatchExercise03 {
    
    
    public static int method(){
    
    
        int i = 1;//1
        try{
    
    
            i++;//2
            String[] names = new String[3];
            if(names[1].equals("tom")){
    
    //NullPointerException
                System.out.println(names[1]);
            } else{
    
    
                names[3] = "hspedu";
            }
            return 1;
        }
        catch (ArrayIndexOutOfBoundsException e){
    
    
            return 2;
        }
        catch (NullPointerException e){
    
    
            //返回3
            return ++i;//3
        }
        finally{
    
    
            ++i;//4
            System.out.println("i = " + i);//i = 4
        }
    }

    public static void main(String[] args) {
    
    
        System.out.println(method());//3
    }
}

TryCatchExercise04 - Get input with exception catch

public class TryCatchExercise04 {
    
    
    /* 1.创建Scanner
     * 2.使用无限循环去接受一个输入
     * 3.然后将输入的值转化为int
     * 4.如果在转化时抛出异常,则说明输入内容不能转化为int
     * 5.如果没有抛出,则break该循环*/
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        int num = 0;
        while (true) {
    
    
            System.out.println("请输入一个整数:\n");
            try {
    
    
                num = Integer.parseInt(scanner.next());
                break;
            } catch (NumberFormatException e) {
    
    
                System.out.println("输入有误,请重新输入!\n");
            }
        }
        System.out.printf("您的输入为: " + num);
    }
}

Throws mechanism

If a method (when the statement in it executes) may generate some kind of exception, but it is not sure how to handle the exception, the method should explicitly declare that the exception is thrown, indicating that the method will not handle the exception.

Use the throws statement in the method to declare the list of thrown exceptions. The exception type behind throws can be the exception type generated in the method, or its parent class.

Throws01.java

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

    }

    //public void f1() throws Exception 也可以
    public void f1() throws FileNotFoundException, NullPointerException {
    
    
        //创建了一个文件流对象
        //这里的异常是一个FileNotFoundException
        //可以使用try-catch
        //也可以使用throws,抛出异常,让调用fi方法的调用者()处理
        //throws关键字后也可以是列表
        FileInputStream fis = new FileInputStream("dd.txt");
    }
}

ThrowsDetail.java

  1. For compilation exceptions, it must be handled in the program, such as try-catch or throws

  2. For runtime exceptions, if there is no processing in the program, the default method is throws

  3. When the subclass overrides the method of the parent class, the rules for throwing exceptions: the type of exception thrown by the method rewritten by the subclass is either the same as that thrown by the parent class, or it is a subtype of the exception type thrown by the parent class.

    class Father {
          
          
        public void method() throws RuntimeException{
          
          
        }
    }
    
    class Son extends Father {
          
          
        //子类重写父类的方法时,对抛出异常的规定:
        // 子类重写的方法所抛出的异常类型要么和父类抛出的一致,
        // 要么为父类抛出异常类型的子类型。
        @Override
        public void method() throws NullPointerException {
          
          
    
        }
    }
    

Compilation exception handling

image-20211008234206117

Solution 1: Use try-catch processing

Solution 2: throws throw

image-20211008234445456

Exception handling

custom exception

When some "error" occurs in the program, but the error is not described in the Throwable subclass, at this time, you can design your own exception class to describe the error message.

Custom exception steps

  1. Definition class: custom exception class name, inheritance ExpectionorRnntimeExpection
  2. If inherited Expection, it is a compilation exception
  3. If inherited RuntimeExpection, it is an abnormal operation (general inheritance RuntimeExpection)

CustomException.java

public class CustomExpection {
    
    
    public static void main(String[] args) {
    
    
        int age = 800;
        //要求年龄在18-120之间1,否则抛出一个异常
        if (!(age >= 18 && age <= 120))
        {
    
    
            throw new AgeException("年龄需要在18~120之间!");
        }
        System.out.println("你的年龄范围正确!");
    }
}

//自定义的一个异常
//1.一般情况,自定义异常都是继承RuntimeException,即运行时异常
//2.好处是,我们可以使用默认的处理机制
class AgeException extends RuntimeException {
    
    
    //构造器
    public AgeException(String message) {
    
    
        super(message);
    }
}

The difference between throw and throws

significance Location something behind
throws A way of exception handling method declaration exception type
throws Keyword to manually generate exception objects method body exception object

Guess you like

Origin blog.csdn.net/weixin_46421722/article/details/122797928