Do you know how to handle these Java exceptions?

华为云开发者社区
中文
Abstract: We are in the process of software development, any language development process cannot do without exception handling.

This article is shared from Huawei Cloud Community " Java Exception Handling Learning Summary ", author: zekelove.

In the process of software development, we cannot do without exception handling in the development of any language. If the exception is not handled, the software will be abnormally interrupted, crashed, and exited, which will seriously affect the user's use and experience. If you apply exception handling reasonably, it will reduce software errors, prompt users friendly, and improve user experience.

What's the exception

Exceptions are some errors in the program, but not all errors are exceptions, and errors can sometimes be avoided. For example: the user inputs illegal data, the divisor is 0 when doing division operations, the statement writes less semicolon, the opened file does not exist, memory overflow, network interruption, etc.

The exception handling mechanism allows the program to deal with the exception in accordance with the pre-set exception handling logic of the code when an exception occurs, so that the program can return to normal and continue execution as much as possible, and keep the code clear.

Exception type

All exception classes in Java are subclasses inherited from java.lang.Exception class. The Exception class is a subclass of the Throwable class. In addition to the Exception class, Throwable also has a subclass Error.

Checked exceptions: exceptions caused by user errors or problems that cannot be foreseen by programmers. In addition to Error and RuntimeException other exceptions.

Runtime exceptions: Runtime exceptions are exceptions that may be avoided by programmers. Error and RuntimeException and their subclasses.

Error: An error is not an exception, but a problem beyond the control of the programmer. The usual practice is to notify the user and suspend the execution of the program.

Common exceptions

Input and output exception: IOException

Arithmetic exception class: ArithmeticExecption

Null pointer exception class: NullPointerException

Type casting exception: ClassCastException

File not found exception: FileNotFoundException

Array subscript out of bounds exception: ArrayIndexOutOfBoundsException

Array negative subscript exception: NegativeArrayException

File has ended exception: EOFException

String conversion to number exception: NumberFormatException

Method not found exception: NoSuchMethodException

Operation database exception: SQLException

Common exception methods

getMessage: Get the detailed information of the exception.

toString: Use the result of getMessage() to return the cascade name of the class.

printStackTrace: Error output stream.

Exception handling

The way to check exception handling: use try...catch...finally block processing; use throws statement in function definition.

syntax:

try{
    // try 块中放可能发生异常的代码。
}catch(ArithmeticException arithexception){
    // 1.每一个 catch 块用于捕获并处理一个特定的异常,或者异常类型的子类。
    // 2.catch 后面括号中定义了异常类型和异常参数。
    // 3.在 catch 块中可以使用这个块的异常参数来获取异常的相关信息。
    // 4.如果 try 块中发生的异常在所有catch中都没捕获到,则去执行finally,然后到这个函数的外部 caller 中去匹配异常处理器。
    // 5.如果 try 中没有发生异常,则所有的catch块都不执行。
}catch(Exception exception){
    // 捕获异常
}finally{
    // 1.finally 块是可选的。
    // 2.无论异常是否发生,finally 都会执行。
    // 3.一个 try 至少要有一个 catch 块,或者至少要有一个 finally 块。
    // 4.finally 块主要做一些关闭清理工作,如关闭文件,关闭数据库连接等。 
}

example

package com.exception;
public class test {
    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        compute();
    }

    public static void compute() {
        try {
            double num = 10 / 0;
            System.out.println(num); 
        }catch(ArithmeticException exp){
            System.out.println(exp.getMessage().toString());
        }finally {
            System.out.println("执行finally块");
        }
    }
}

Keyword throws/throw

If a method does not catch a checked exception, then the method must be declared using the throws keyword, which is placed at the end of the definition method.

You can also use the throw keyword to throw an exception, whether it is newly instantiated or just caught.

throws syntax:

Modifier return value type method name (parameter) throws exception class name 1, exception class name 2, ... {code block}

package com.exception;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class test {

    public static void main(String[] args) throws FileNotFoundException {
        // TODO 自动生成的方法存根
        readFile();
    }
 
    public static  void readFile() throws FileNotFoundException {
        InputStream file = new FileInputStream("E:/test.txt");
    }
}

throw Syntax:

throw new xxxException();

Where xxxException must be a derived class of Exception.

Note: What is thrown is an exception object, so new cannot be omitted.

Custom exception

In addition to the exception classes defined by the JDK, we can customize the exception handling classes according to our own business conditions.

Points to note when writing custom exception classes:

1. All exceptions must be a subclass of Throwable.

2. If you write a checked exception class, you need to inherit the Exception class.

3. If you write a runtime exception class, you need to inherit the RuntimeException class.

Syntax: modifier class class name extends Exception {code block}

package com.exception;
/**
 * 自定义异常类
 * 登录失败异常信息类
*/
public class LoginFailException extends RuntimeException {
    public LoginFailException() {
        super();
    }
    public LoginFailException(String message) {
        super(message);
    }
    public void printStackTrace(){ 
        //overwrite  
        super.printStackTrace();  
        System.out.printf("This is a LoginFailException excetpion\n");    
    }  
}
public class test {

    public static void main(String[] args){
        // TODO 自动生成的方法存根
        Boolean isLogin = false;
        if(!isLogin) {
            // 登录失败,抛出异常
            throw new LoginFailException("Login is fail");
        }
    }
}

Click to follow and learn about Huawei Cloud's fresh technology for the first time~

阅读 582

开发者之家
华为云开发者社区,提供全面深入的云计算前景分析、丰富的技术干货、程序样例,分享华为云前沿资讯动态...

华为云开发者社区,提供全面深入的云计算前景分析、丰富的技术干货、程序样例,分享华为云前沿资讯动态...

1.2k 声望
1.7k 粉丝
0 条评论

华为云开发者社区,提供全面深入的云计算前景分析、丰富的技术干货、程序样例,分享华为云前沿资讯动态...

1.2k 声望
1.7k 粉丝
文章目录
宣传栏