A detailed introduction to Java exception capture and handling

1. Brief description of the exception

1. Three types of exceptions

  • Examination abnormality: The most representative checked exception is the exception caused by user error or problem, which cannot be foreseen by the programmer. For example, when opening a file that does not exist, an exception occurs. These exceptions cannot be simply ignored during compilation.
  • Runtime exception: Runtime exceptions are exceptions that may be avoided by programmers. In contrast to checked exceptions, runtime exceptions can be ignored at compile time.
  • error: An error is not an exception, but a problem beyond the control of the programmer. Errors are usually ignored in the code. For example, when the stack overflows, an error occurs, and they cannot be checked during compilation.

2. Abnormal hierarchy

The Throwable class is the super class of all errors (Error) or exceptions (Exception) in the Java language.

  • Error: Errors in the program cannot be handled and can be avoided.
  • Exception: There are mainly two subclasses of IOException class and RuntimeException class.

Insert picture description here

3. Understand exception handling

Error: can only be solved by modifying the source code

//OutOfMemoryError: Java heap space 内存溢出错误
int arr[] = new int[1024*1024*1024];

Exception: specific processing can be carried out to make the program continue to run

1. Use the throw keyword to handle
2. Use the throws keyword to throw an exception when the method is declared
3. Use the try catch finally keyword to catch the thrown exception

2. Exception handling

1.Java exception handling process

1. JVM encounters an exception 创建异常对象(object content includes: content, reason, location)
2. Look for try catch or method throws 异常抛出, if no exception is thrown, it will be directly handed over to JVM for processing
3. JVM according to the received 异常信息在控制台进行打印, if If no exception is thrown, the program is terminated

A simple exception program example
Insert picture description here

2. Exception handling

throw keyword

effect

Throw an exception

format

throw new xxxException("异常产生的原因")

Code example

//定义一个空数组
int[] arr = null;
//判断数组是否为空
if(arr == null){
    
    
	//如果 if 判断成立,则使用 throw 关键字抛出异常
    throw new NullPointerException("数组传递过来为空");
}
//定义一个长度为 5 的数组
int[] arr = new int[5];
//设置 arr 数组的一个索引值
int index = 5;
//判断数组索引是否越界
if(index < 0 || index > arr.length - 1 ){
    
    
	//如果 if 判断成立,则使用 throw 关键字抛出异常
    throw new ArrayIndexOutOfBoundsException("数组索引越界了");
}

Precautions

1. Throw keyword must be 写在方法的内部
2. Throw keyword behind new的对象必须是Exception或者Exception子类对象
3. Throw keyword throws the specified exception object, we must deal with this exception object

  • If you create a RuntimeException or a subclass of RuntimeException, you can leave it to JVM (print exception and terminate the program) by default.
  • If you create a compilation exception (an error is reported when writing code), you must handle this exception

throws keyword

effect

When an exception object is thrown inside a method, the exception object must be handled.
You can use the throws keyword to handle the exception object, and the exception object declaration will be thrown to the caller of the method for processing (not handled by yourself, but handled by others), and finally handed over to the JVM for processing → interrupt processing.

format

修饰符 返回值类型 方法名(参数列表) throws xxxExcepiton, yyyExcepiton, ...{
    
    
    throw new xxxExcepiton("xxx异常产生原因");
    throw new yyyExcepiton("yyy异常产生原因");
    ...
}

Code example

public void test() throws /*FileNotFoundException*/ IOException{
    
    
	/*
    FileNotFoundException extends IOException
    如果抛出的多个异常对象有子父类关系,那么直接声明父类异常即可
    */

    //定义一个目标文件路径
    String file = "c:\\exception.txt";
    
    //传递 c:\error.txt 与目标文件路径比较
    if(!file.equals("c:\\error.txt")) {
    
    
        throw new FileNotFoundException("文件路径不是c:\\exception.txt");
    }
    
    //传递 c:\exception.doc 与目标文件路径比较
    if(!file.endsWith("c:\\exception.doc")){
    
    
        throw new IOException("文件的后缀名不是.txt");
    }
}

Precautions

1. Throws keyword 必须写在方法声明处
2. The exception declared after the throws keyword must be Exception or a subclass of Exception
3. If multiple exception objects are thrown inside the method, then multiple exceptions must also be declared after throws

  • If 抛出的多个异常对象有子父类关系,那么直接声明父类异常即可

4. A method that declares an exception is called, and the declared exception must be handled

  • Either continue to use the throws statement to throw, hand it over to the caller of the method, and finally hand it over to the JVM
  • Either try...catch to handle the exception

try catch finally keyword

try : Catch the exception.
catch : handle exceptions.
finally : Regardless of whether an exception occurs, the contents of the finally block will be executed.

effect

When an exception object is thrown inside a method, the exception object must be handled.
You can use the try catch keyword 捕获、处理exception object, which is handled by the programmer according to the situation.

Format
catch 块的数量是由 try 语句捕获的异常数量决定的 , in most cases there is only one catch block.
finally 块可有可无.

try{
    
    
    可能产生异常的代码
}catch(异常类名 变量名){
    
    
    异常的处理逻辑,异常异常对象之后,怎么处理异常对象
    一般在工作中,会把异常的信息记录到一个日志中
}
...
catch(异常类名 变量名){
    
    
	...
}finally{
    
    
    无论是否出现异常都会执行
}

Code example

public class DemoTryCatchFinally {
    
    
    public static void main(String[] args) {
    
    
        //定义一个目标文件路径
        String file = "c:\\exception.txt";
        
        try {
    
    
            //传递 c:\error.txt 与目标文件路径比较
            if(!file.equals("c:\\error.txt")) {
    
    
                throw new FileNotFoundException("文件路径不是c:\\exception.txt");
            }
        } catch (IOException e) {
    
    
            //异常的处理逻辑
            //方法一
            System.out.println(e.getMessage());
            //方法二
			System.out.println(e.toString());
			//方法三(最常用)
            e.printStackTrace();
        } finally {
    
    
            //无论是否出现异常,都会执行
            System.out.println("资源被释放了");
        }
    }
}

In the Throwable class, the superclass of the exception class, three exception handling methods are defined, Choose the appropriate one according to your needs when you use it.

String getMessage()      返回此 throwable 的简短描述。
String toString()        返回此 throwable 的详细消息字符串。
void printStackTrace()   JVM打印异常对象,默认此方法,打印的异常信息是最全面的。

Multiple exception handling

  1. Multiple exceptions are handled separately
    每一个异常使用一对 try catch
    
  2. Capture multiple exceptions once and handle multiple exceptions
    使用一个 try 多个 catch
    
  3. Multiple exceptions are caught at one time and processed at one time
    使用一个 try 一个 catch
    

Precautions

1. Whether an exception occurs in try

  • If an exception occurs in the try, then the exception handling logic in the catch will be executed, the processing logic in the catch will be executed, and the code after the try...catch will continue.
  • If there is no exception in the try, then the processing logic of the exception in the catch will not be executed. After executing the code in the try, continue to execute the code after the try...catch

2.finally cannot be used alone, must be used together with try
3.finally is generally used for resource release (resource recovery), no matter whether the program is abnormal or not, the resource must be released (IO) at the end
4.如果try和finally同时存在 return 语句,那么try的返回值会被finally中的返回值替换掉

Three, custom exception

The exception classes provided by Java cannot meet all actual needs. You need to define some exception classes yourself.
format

public class xxxException extends Exception | RuntimeException{
    
    
     添加一个空参数的构造方法
     添加一个带异常信息的构造方法
}

Code example
Define custom exception class

public class DemoException extends Exception{
    
    

    //添加一个空参数的构造方法
    public DemoException(){
    
    
        super();
    }

    /*
    添加一个带异常信息的构造方法
    查看源码发现,所有的异常类都会有一个带异常信息的构造方法,方法内部会调用父类带异常信息的构造方法,让父类来处理这个异常信息
    */
    public DemoException(String massage){
    
    
        super(massage);
    }
    
}

Use custom exception class

public class DemoExceptionTest {
    
    


    public static void main(String[] args) throws DemoException {
    
    
        test01();
        test02();
    }

    //使用 throws 关键字抛出异常
    private static void test01() throws DemoException {
    
    
        throw new DemoException("自定义异常");
    }

    //使用 try catch 捕获并抛出异常
    private static void test02() {
    
    
        try {
    
    
            throw new DemoException("自定义异常");
        } catch (DemoException e) {
    
    
            e.printStackTrace();
        }
    }
}

Precautions

1. Custom exception classes generally end with Exception, indicating that the class is an exception class
2.自定义异常类,必须的继承Exception或者RuntimeException

  • 继承 Exception类: Then the custom exception class is a compile-time exception. If a compile-time exception is thrown inside the method 必须处理这个异常, either throws or try...catch...
  • 继承RuntimeException类: Then the custom exception class is a runtime exception 无需处理,, handed over to the virtual machine for processing (interrupt processing)

Guess you like

Origin blog.csdn.net/weixin_44580492/article/details/107915498