Table of Contents
1. Causes and classification of exceptions" >1. Causes and classification of exceptions
1.1 Causes of exceptions" >1.1 Causes of exceptions
1.2 Exception classification" >1.2 Exception classification
2.2 异常的抛出(throw)" >2.2 异常的抛出(throw)
2.3 异常的捕获" >2.3 异常的捕获
2.3.1 throws异常声明" >2.3.1 throws异常声明
2.3.2 try-catch捕获异常并处理 " >2.3.2 try-catch捕获异常并处理
2.3.3 finally" >2.3.3 finally
3.自定义异常类" >3.自定义异常类
Home Java javaTutorial Let's analyze the causes and processing of exceptions in Java

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

May 31, 2022 am 11:31 AM
java

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();
    }
}
Copy after login


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;
        }
    }
Copy after login

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

 (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;
        } 
    }
Copy after login

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

处理异常的核心思想就是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);
    }
Copy after login

 注意:

(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();
        }
    }
Copy after login

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

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

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

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

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("其他程序!");
    }
Copy after login

如果程序抛出异常,不处理异常,那就会交给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("其它代码逻辑!");
    }
Copy after login

也可以简写一下

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

 如果异常之间具有父子关系,那就必须子类异常在前,父类异常在后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("其它代码逻辑!");
    }
Copy after login

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

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

所以,不管程序会不会抛出异常,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("其它代码逻辑!");
    }
Copy after login

 下面看这一段代码

    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));
    }
Copy after login

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

 总结一下:

throw抛出异常,throws声明异常

finally语句一定会执行

3.自定义异常类

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

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

举一个例子

先自定义一个运行时异常

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

    }
    public MyException(String message) {
        super(message);
    }
}
Copy after login

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

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

    }
}
Copy after login

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

class UserNameException extends RuntimeException {
    public UserNameException() {

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

    public PasswordException() {
    }

    public PasswordException(String message) {
        super(message);
    }
}
Copy after login
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();
        }
    }
}
Copy after login

注意:

自定义异常默认会继承 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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles