Home  >  Article  >  Java  >  Let's analyze the causes and processing of exceptions in Java

Let's analyze the causes and processing of exceptions in Java

WBOY
WBOYforward
2022-05-31 11:31:332820browse

This article brings you relevant knowledge about java, which mainly introduces issues related to exceptions. Exceptions, also known as exceptions, are events that occur during program execution. Interrupt the normal instruction flow of the executing program. Let's take a look at it. I hope it will be helpful to everyone.

Let's analyze the causes and processing of exceptions in Java

Recommended study: "java Video Tutorial"

Exception in Java ), also known as an exception, is an event that occurs during program execution that interrupts the normal flow of instructions in the executing program. In order to handle running errors in the program promptly and effectively, exception classes must be used.

1. Causes and classification of exceptions

1.1 Causes of exceptions

Exceptions occur in Java for three main reasons:

(1) Errors in writing program code Exceptions generated, such as array out-of-bounds, null pointer exceptions, etc., are called unchecked exceptions. Generally, these exceptions need to be handled in the class

(2 ) An exception occurs when an internal error occurs in Java. The Java virtual machine generates an exception

(3) An exception manually generated through the throw statement. This exception Exceptions called checks are generally used to give the method caller some necessary information

1.2 Exception classification

(1) Throwable: It is the top-level class of the exception system, which derives two important subclasses, Error and Exception

The two subclasses Error and Exception represent errors and exceptions respectively.

The difference is Unchecked Exception and Checked Exception.

(2) The Exception class is used for exceptions that may occur in user programs. It is also a class used to create custom exception type classes.

# (3) Error defines exceptions that are not expected to be caught by the program under normal circumstances. Exceptions of type Error are used by the Java runtime to display errors related to the runtime system itself. Stack overflow is an example of this error.

Exceptions may occur during compilation or while the program is running. Depending on the timing of occurrence, they can be divided into:

Runtime exceptions are exceptions of the RuntimeException class and its subclasses, such as NullPointerException, IndexOutOfBoundsException, etc. These exceptions are not checked exceptions, and you can choose to capture them in the program, or It doesn’t need to be processed. These exceptions are generally caused by program logic errors, and the program should try to avoid the occurrence of such exceptions from a logical perspective.

For example:

##Compile-time exception refers to exceptions other than RuntimeException , all types belong to the Exception class and its subclasses. From the perspective of program syntax, it is an exception that must be handled. If it is not handled, the program will not be compiled. Such as IOException, ClassNotFoundException, etc. and user-defined Exception exceptions. Generally, no custom checked exceptions are used.

For example

class Person implements Cloneable{
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
public class Test01 {

    public static void main(String[] args) {
        Person person =new Person();
        Person person1 =(Person) person.clone();
    }
}


2. Exception handling

2.1 Defensive programming

Errors exist objectively in the code. SoWhen there is a problem with the program Quickly notify programmers.

There are two ways to notify:

(1) LBYL does sufficient checks before operating

private static int pide() {
        int a = 0, b = 0;
        Scanner scanner = new Scanner(System.in);
        a = scanner.nextInt();
        b = scanner.nextInt();
        if (b == 0) {
            System.out.println("除数为0");
            return 0;
        } else {
            return a / b;
        }
    }

缺点:正常流程和错误处理流程代码混在一起, 代码整体条理不清晰。

 (2)EAFP 先操作遇到问题再处理

private static int pide() {
        int a = 0, b = 0;
        try (Scanner scanner = new Scanner(System.in)) {
            a = scanner.nextInt();
            b = scanner.nextInt();
            return a / b;
        } catch (ArithmeticException exception) {
            System.out.println("除数为0");
            return 0;
        } 
    }

优点:正常流程和错误流程是分离开的, 程序员更关注正常流程,代码更清晰,容易理解代码

处理异常的核心思想就是EAFP 

2.2 异常的抛出(throw)

在编写程序时,如果程序中出现错误,这就需要将错误的信息通知给调用者

这里就可以借助关键字throw,抛出一个指定的异常对象,将错误信息告知给调用者。

 比如写一个运行时异常

    public static void func2(int a) {
        if(a == 0) {
           //抛出的是一个指定的异常,最多的使用方式是,抛出一个自定义的异常
            throw new RuntimeException("a==0");
        }
    }
    public static void main(String[] args) {
        func2(0);
    }

 注意:

(1)throw必须写在方法体内部

(2)如果抛出的是编译时异常,用户就必须要处理,否则无法通过编译

(3)如果抛出的运行时异常,则可以不用处理,直接交给JVM来处理

(4)一旦出现异常,后面的代码就不会执行

2.3 异常的捕获

2.3.1 throws异常声明

  throws处在方法声明时参数列表之后,当方法中抛出编译时异常,用户不想处理该异常,

此时就可以借助throws将异常抛 给方法的调用者来处理。

格式:  

修饰符 返回值类型 方法名(参数列表) throws 异常类型 {  

}  

 如果说方法内部抛出了多个异常,throws之后就必须跟多个异常类型,用逗号进行分隔

    public static void func2(int a) throws CloneNotSupportedException, FileNotFoundException {
        if(a == 0) {
            throw new CloneNotSupportedException("a==0");
        }
        if(a == 1) {
            throw new FileNotFoundException();
        }
    }

   如果抛出多个异常类型有父子关系,直接声明父类 

    public static void func2(int a) throws Exception {
        if(a == 0) {
            throw new CloneNotSupportedException("a==0");
        }
        if(a == 1) {
            throw new FileNotFoundException();
        }
    }

调用声明抛出异常的方法时,调用者必须对该异常进行处理,或者继续使用throws抛出

   public static void main(String[] args) throws FileNotFoundException, CloneNotSupportedException {
        func2(0);
    }

2.3.2 try-catch捕获异常并处理

当程序抛出异常的时候,程序员通过try-each处理了异常

    public static void main(String[] args) {
        try {
            int[] array = null;
            System.out.println(array.length);
        }catch (NullPointerException e) {
            System.out.println("捕获到了一个空指针异常!");
        }
        System.out.println("其他程序!");
    }

如果程序抛出异常,不处理异常,那就会交给JVM处理,JVM处理就会把程序立即终止

并且,即使用了try-each 也必须捕获一个对应的异常,如果不是对应异常,也会让JVM进行处理

  如果try抛出多个异常,就必须用多个catch进行捕获

这里注意,用多个catch进行捕获,不是同时进行捕获的,因为不可能同时抛不同的异常

    public static void main(String[] args) {
        try {
            int[] array = null;
            System.out.println(array.length);
        }catch (NullPointerException e) {
            System.out.println("捕获到了一个空指针异常!");
        }catch (ArithmeticException e) {
            System.out.println("捕获到了一个算术异常!");
        }
        System.out.println("其它代码逻辑!");
    }

也可以简写一下

    public static void main(String[] args) {
        try {
            int[] array = null;
            System.out.println(array.length);
        }catch (NullPointerException  | ArithmeticException e) {
            System.out.println("捕获到了一个空指针或算术异常!");
        }
        System.out.println("其它代码逻辑!");
    }

 如果异常之间具有父子关系,那就必须子类异常在前,父类异常在后catch,不然会报错  

    public static void main(String[] args) {
        try {
            int[] array = null;
            System.out.println(array.length);
        }catch (NullPointerException e) {
            System.out.println("捕获到了一个空指针异常!");
        }catch (Exception) {
            System.out.println("捕获到了一个算术异常!");
        }
        System.out.println("其它代码逻辑!");
    }

2.3.3 finally

 finally用来进行资源回收,不论程序正常运行还是退出,都需要回收资源

并且异常会引发程序的跳转,可能会导致有些语句执行不到

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        try {
            int[] array = null;
            System.out.println(array.length);
        }catch (NullPointerException e) {
            System.out.println("捕获到了一个空指针异常!");
        }catch (ArithmeticException e) {
            System.out.println("捕获到了一个算术异常!");
        }finally {
            scanner.close();
            System.out.println("进行资源关闭!");
        }
        System.out.println("其它代码逻辑!");
    }

 如果不为空,那么finally还会被执行吗

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        try {
            int[] array = {1,2,3};
            System.out.println(array.length);
        }catch (NullPointerException e) {
            System.out.println("捕获到了一个空指针异常!");
        }catch (ArithmeticException e) {
            System.out.println("捕获到了一个算术异常!");
        }finally {
            scanner.close();
            System.out.println("进行资源关闭!");
        }
        System.out.println("其它代码逻辑!");
    }

所以,不管程序会不会抛出异常,finally都会执行

 如果将资源写在try中会自动帮助,关掉资源的

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            int[] array = {1, 2, 3};
            System.out.println(array.length);
        } catch (NullPointerException e) {
            System.out.println("捕获到了一个空指针异常!");
        } catch (ArithmeticException e) {
            System.out.println("捕获到了一个算术异常!");
        } finally {
            System.out.println("进行资源关闭!");
        }
        System.out.println("其它代码逻辑!");
    }

 下面看这一段代码

    public static int func(int a) {
        try{
            if(a == 0) {
                throw  new ArithmeticException();
            }
            return a;
        } catch (ArithmeticException e) {
            System.out.println("算术异常!");
        } finally {
            return 20;
        }
    }

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

 可以发现即使有return,finally也会被执行

 总结一下:

throw抛出异常,throws声明异常

finally语句一定会执行

3.自定义异常类

虽然java中有很多异常类,但是在实际开发中所遇到的一些异常,不能完全表示,

所以这就需要我们自定义异常类

举一个例子

先自定义一个运行时异常

//自定义了一个运行时异常
public class MyException extends RuntimeException{
    public MyException() {

    }
    public MyException(String message) {
        super(message);
    }
}

写一个类来捕获这个自定义异常

public class Test04 {
    public static void func(int a ) {
        throw new MyException("呵呵!");
    }

    public static void main(String[] args) {
        try {
            func(20);
        }catch (MyException myException) {
            myException.printStackTrace();
        }finally {
            System.out.println("sadasdasd");
        }

    }
}

下面写一个用户登录的自定义异常类

class UserNameException extends RuntimeException {
    public UserNameException() {

    }
    public UserNameException(String message) {
        super(message);
    }
}
class PasswordException extends RuntimeException {

    public PasswordException() {
    }

    public PasswordException(String message) {
        super(message);
    }
}
public class LogIn {
    private static String uName = "admin";
    private static String pword = "1111";

    public static void loginInfo(String userName, String password) {
        if ( !uName.equals(userName)) {
            throw new UserNameException("用户名错误!");
        }
        if ( !pword.equals(password)) {
            throw new RuntimeException("密码错误!");

        }
        System.out.println("登录成功!");
    }

    public static void main(String[] args) {
        try {
            loginInfo("admin","1111");
        } catch (UserNameException e) {
            e.printStackTrace();
        } catch (PasswordException e) {
            e.printStackTrace();
        }
    }
}

注意:

自定义异常默认会继承 Exception 或者 RuntimeException    

继承于 Exception 的异常默认是受查异常    

继承于 RuntimeException 的异常默认是非受查异常   

推荐学习:《java视频教程

The above is the detailed content of Let's analyze the causes and processing of exceptions in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete