Java learning record (intermediate)-[1], exception handling

(1) Exception definition: The event that causes the normal flow of the program to be interrupted is called an exception.

(2) Common methods of exception handling : [try-catch], [try-catch-finally], [throws]

Note: try-catch-fianlly

Regardless of whether an exception occurs, the code in finally will be executed;

If there is a return in the try block, the statement in the finally block will be executed first, and then return.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class FinallyTest {

	public static void main(String[] args) {
		File f = new File("a.txt");

		String result = open(f);
		System.out.println(result);
	}

	public static String open(File f) {
		FileInputStream fs = null;
		try {
			System.out.println("试图打开 a.txt");
			fs = new FileInputStream(f);
			return "成功打开!";
		} catch (FileNotFoundException e) {
			System.out.println("a.txt不存在");
			e.printStackTrace();
			return "打开失败";
		} finally {
			System.out.println("无论文件是否存在, 都会执行的代码");
		}
	}

}

Output result:

(3), abnormal classification

总体上异常分三类: 
1. 错误
2. 运行时异常
3. 可查异常

ä¸ç§åç±»

[1]. Checked exception CheckedException : that is , the exception that must be handled , either try-catch it or throw it out, whoever calls it, who handles it, such as FileNotFoundException;

If it is not processed, the compilation fails.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class CheckedExceptionTest {
	
	public static void main(String[] args) {
        
        File f= new File("d:/LOL.exe");
          
        try{
            System.out.println("试图打开 d:/LOL.exe");
            new FileInputStream(f);
            System.out.println("成功打开");
        }
        catch(FileNotFoundException e){
            System.out.println("d:/LOL.exe不存在");
            e.printStackTrace();
        }
          
    }

}

operation result:

[2], Runtime Exception RuntimeException : it  is not necessary to try catch exception

常见运行时异常: 
除数不能为0异常:     ArithmeticException 
下标越界异常:        ArrayIndexOutOfBoundsException 
空指针异常:          NullPointerException 

When writing code, you can still use try-catch and throws for processing. The difference with checkable exceptions is that even if try catch is not performed, there will be no compilation errors ; the
reason why Java designs runtime exceptions First, because the subscript is out of bounds and the runtime exceptions such as null pointers are too common, if all of them need to be caught, the readability of the code will become very bad.

public class ExceptionTest {
	
	public static void main(String[] args) {
        
        //任何除数不能为0:ArithmeticException
        int k = 5/0;
         
        //下标越界异常:ArrayIndexOutOfBoundsException
        int j[] = new int[5];
        j[10] = 10;
         
        //空指针异常:NullPointerException
        String str = null;
        str.length();
   }

}

Running result: The compilation can pass, but an error will be reported when running.

[3], Error Error : Refers to system-level exceptions, usually memory is used up .
Under the default settings, when a general java program is started, a maximum of 16m of memory can be used;
[Note: As with runtime exceptions, errors are not required to be forced to capture]
For example: keep adding characters to StringBuffer, and it will soon Used up the memory. Throws OutOfMemoryError

public class ErrorTest {

	public static void main(String[] args) {
		StringBuffer sb =new StringBuffer();
        
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            sb.append('a');
        }
	}

}

operation result:

The program will run for a few seconds first, and then suddenly an error is reported: ↓ ↓ ↓ 

(4)、Throwable 

Throwable is a class, both Exception and Error inherit this class;

So when capturing, you can also use Throwable to capture.

As shown in the figure: Exceptions are divided into Error and Exception
Exception, which are divided into runtime exceptions and checkable exceptions.

Throwable

import java.io.File;
import java.io.FileInputStream;

public class ThrowableTest {
	
	public static void main(String[] args) {
		 
        File f = new File("d:/LOL.exe");
 
        try {
            new FileInputStream(f);
        } catch (Throwable t) {    //使用Throwable进行异常捕捉
            t.printStackTrace();
        }
 
    }

}

operation result:

(5) Create a custom exception

public class MyException extends Exception{
    
    public MyException(){
         
    }

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

}

Guess you like

Origin blog.csdn.net/qq_37164975/article/details/82625634