Java SE:异常

Java SE:异常

1、Throwable 异常

/*
异常:
        Throwable
        /       \
     Error      Exception
*/

**Error: 错误,**一般指代由虚拟机生成并脱出的问题,不由程序猿控制

  • Exception: 异常
    • CheckedException 检查时异常 | 编译时异常
    • RuntimeException 运行时异常
      增强程序的健壮性决定( if… )

2、常见的运行异常

  • 1.空指针
  • 2.索引越界 ArrayIndexOutOfBoundsException
  • 3.数学异常 ArithmeticException
  • 4.数据格式异常 NumberFormatException
public static void main(String[] args) {
        //运行时期异常
        String s = null;
        //空指针 NumberFormatException
        if(s!=null){
            System.out.println(s.length());
        }

        int[] arr = new int[2];
        //索引越界  ArrayIndexOutOfBoundsException
        //System.out.println(arr[3]);

        //System.out.println(5/0);

        s = "123abc";
        System.out.println(Integer.valueOf(s));;
        System.out.println("main方法结束");

        //编译时异常
        //InputStream is = new FileInputStream("D://hahaha.txt");
    }

3、异常处理

  对于编译(非运行)时异常( checked exception ),必须要对其进行处理,否则无法通过编译。

运行时异常(Runtime Exception)在运行时报错。处理方式有两种:

  • 异常捕获 throws
  • 异常抛出 try…catch…finally

3.1 抛出异常 throws

  • 把异常抛出到上一层,谁调用谁解决
  • 方法或类后面加throws关键字
static void test() throws FileNotFoundException {
        //编译时异常
        InputStream is = new FileInputStream("D://hahaha.txt");
    }

3.2 异常捕获

  • 一个try后面可以跟一到多个catch… ;范围大的catch一定要写在后面
  • 如果try中的代码没有出现异常,try中的正常执行完毕
  • 如果try中一旦遇到异常,try中后面的代码不会执行,直接执行catch进行判断,从上到下进行判断,找到能够接受当前出现异常对象的catch,直接执行对应的语句体
  • 无论是否try中出现异常,无论异常是否能够捕获,都会在结束之前执行finally中的代码
try{
      有可能出现异常的代码;
}catch(NullPointerException e){
      执行对应的代码...
}catch(Exception e){
      e....;
 //如果出现种异常,执行的代码
}finally{
      无论是否出现异常,都会执行finally的代码
}

注意:

  • 一个异常出现如果不处理,后面程序无法执行
  • 一个异常出现,如果通过异常处理方案进行处理后,后面代码可能正常执行
public class ExceptionDemo02 {
    public static void main(String[] args) {
        try {
            System.out.println("try开始了");
            test();
            System.out.println(5/0);

            System.out.println("try结束了");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            System.out.println("最后的最后我们都要离开....");
        }

        System.out.println("main方法结束了");
    }

    static void test() throws FileNotFoundException {
        //编译时异常
        InputStream is = new FileInputStream("D://hahaha.txt");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值