Home  >  Article  >  Java  >  Causes of exceptions in Java and how to deal with them

Causes of exceptions in Java and how to deal with them

王林
王林forward
2023-04-20 12:37:06937browse

Causes of exceptions in Java and how to deal with them

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

1. Causes and classifications of exceptions

1.1 Reasons for exceptions

There are three main types of exceptions in Java Reason:

(1) Exceptions caused by errors in writing program code, such as array out-of-bounds, null pointer exceptions, etc. This type of exception is called an unchecked exception and generally requires Handle these exceptions in the class

(2) Exceptions caused by Java internal errors, the Java virtual machine generates exceptions

(3) Through throw (Throw exception) Exception manually generated by the statement. This exception is called a checked exception. It is generally used to give the method caller some necessary information

1.2 Exception classification

Causes of exceptions in Java and how to deal with them

(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 all exceptions of the RuntimeException class and its subclasses, such as NullPointerException, IndexOutOfBoundsException, etc. These exceptions are unchecked exceptions, and you can choose to capture or not process them in the program. 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:

Causes of exceptions in Java and how to deal with them

Compile-time exceptions refer to exceptions other than RuntimeException, and all types belong to 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();
    }
}

Causes of exceptions in Java and how to deal with them

2. Exception handling

2.1 Defensive programming

Errors exist objectively in the code. Therefore, when there is a problem with the program, the programmer must be notified quickly.

There are two ways to notify:

(1) LBYL Do adequate checks before operation

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;
        }
    }

Disadvantages: The normal process and error handling process codes are mixed together, and the overall code is not clear.

(2) EAFP operates first and then handles problems when encountering them

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;
        } 
    }

Advantages: Normal processes and error processes are separated, programmers Pay more attention to the normal process, the code is clearer, and it is easy to understand the code

The core idea of ​​handling exceptions is EAFP

2.2 Exception throwing Throw (throw)

When writing a program, if an error occurs in the program, the error information needs to be notified to the caller

Here you can use the keyword throw to throw a specified exception object and inform the caller of the error message.

For example, write a runtime exception

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

Causes of exceptions in Java and how to deal with them Note:

##(1 ) throw must be written inside the method body

(2) If a compile-time exception is thrown, the user must handle it, otherwise it will not pass the compilation

Causes of exceptions in Java and how to deal with them

(3) If a runtime exception is thrown, it does not need to be processed and is directly handed over to the JVM for processing

(4) Once an exception occurs, the following code will not be executed

Causes of exceptions in Java and how to deal with them

2.3 异常的捕获

2.3.1 throws异常声明

Causes of exceptions in Java and how to deal with them

 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进行处理

Causes of exceptions in Java and how to deal with them

 如果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("其它代码逻辑!");
    }

Causes of exceptions in Java and how to deal with them

如果不为空,那么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("其它代码逻辑!");
    }

Causes of exceptions in Java and how to deal with them

所以,不管程序会不会抛出异常,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));
    }

Causes of exceptions in Java and how to deal with them

可以发现即使有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 的异常默认是非受查异常  

The above is the detailed content of Causes of exceptions in Java and how to deal with them. For more information, please follow other related articles on the PHP Chinese website!

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