Java学习记录(中级)——【1】、异常处理

(1)、异常定义:导致程序的正常流程被中断的事件,叫做异常。

(2)、异常处理常见手段【 try-catch 】、【 try-catch-finally 】、【 throws 】

注意:try-catch-fianlly

无论是否出现异常,finally中的代码都会被执行;

如果try块中有return,那么会先执行finally块中的语句,然后再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("无论文件是否存在, 都会执行的代码");
		}
	}

}

输出结果:

(3)、异常分类

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

ä¸ç§åç±»

[1]、可查异常 CheckedException : 即必须进行处理的异常,要么try-catch住,要么往外抛,谁调用,谁处理,比如 FileNotFoundException;

如果不处理,则编译无法通过。

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

}

运行结果:

[2]、运行时异常 RuntimeException : 不是必须进行try catch的异常

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

在编写代码的时候,依然可以使用try-catch、throws进行处理,与可查异常不同之处在于,即便不进行try catch,也不会有编译错误
Java之所以会设计运行时异常的原因之一,是因为下标越界,空指针这些运行时异常太过于普遍,如果都需要进行捕捉,代码的可读性就会变得很糟糕。

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

}

运行结果:编译可以通过,但运行时会报错。

[3]、错误 Error : 指的是系统级别的异常,通常是内存用光了
在默认设置下,一般java程序启动的时候,最大可以使用16m的内存;
【注意:与运行时异常一样,错误也是不要求强制捕捉的】
如例:不停的给StringBuffer追加字符,很快就把内存使用光了。抛出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');
        }
	}

}

运行结果:

程序首先会运行几秒,然后,突然报错:↓ ↓ ↓ 

(4)、Throwable 

Throwable是类,Exception和Error都继承了该类;

所以在捕捉的时候,也可以使用Throwable进行捕捉。

如图: 异常分Error和Exception
Exception里又分运行时运行时异常和可查异常。

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

}

运行结果:

(5)、创建自定义异常

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

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

}

猜你喜欢

转载自blog.csdn.net/qq_37164975/article/details/82625634