异常捕获

阅读量: 4 编辑

一、异常捕获介绍

1、try-catch 来捕获异常;

2、一个 try 可以多个 catch 配合使用;

3、不需要捕获异常的代码可以放在 try-catch 中,也可以不放;

4、代码块中抛出哪个异常,就执行异常对应的代码块,就是对应的 catch

5、finally 无论如何都会执行;

二、语法

try{
    // 可能会抛出特定异常的代码段
    
}catch(ExceptionType exception){
    // 如果Exception 被抛出,则执行这段代码
    
}catch(ExceptionType otherException){
    //如果另外的异常otherException被抛出,则执行这段代码
    
} [finally{
    //无条件执行的语句
    
}]

三、编程实战

代码的详细解读,可以参考视频教程

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * User: 祁大聪
 */
public class S21 {

    public static void testArr(){
        try{
            int[] arr = {1,2,3,4,5,6};
            System.out.println(arr[2]);//下标最大是5
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("finally is called");
        }
        System.out.println("==================");
    }

    public static void testFile() {
        // ctrl + alt + t
        FileInputStream fis = null;
        try {
            String filePath = "E://a.log";
            fis = new FileInputStream(filePath);
            byte[] b = new byte[1024];
            while(fis.read(b) != -1){

            }
            fis.close();
        }catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("-------------------- FileNotFoundException");
        }  catch (IOException e) {
            e.printStackTrace();
            System.out.println("------------------------- IOException");
        } finally {
            System.out.println("finally is called");
        }
        System.out.println("==================");
    }

    public static void main(String[] args) {
        testFile();
    }
}

爱码岛编程公众号
试卷资料
爱码岛编程小程序
在线刷题
苏ICP备13052010号
©2023 南京匠成信息科技有限公司