异常的使用

  1. Java程序运行过程中的异常事件可分为:
  • 错误(Error:JVM系统内部错误、资源耗尽等严重情况
  • 异常(Exception:其他因编译程序错误或偶然的外在因素导致的一般性问题

集中常见的异常:

  • 空指针访问
  • 视图读取不存在的文件
  • 数组越界异常
  • 网络中断异常

异常捕获

  1. try-catch来捕获异常
  2. 一个try可以多个catch配合使用
  3. 不需要捕获异常的代码可以放在try-catch中,也可以不放
  4. 代码块中抛出哪个异常,就执行异常对应的代码块,对视对应的catch
  5. finally无论如何都会执行

 try{

        //可能抛出异常的代码块

}catch(Exception e){

        //如果异常被抛出,则执行这段代码

}catch(ExceptionType e){

        //如果另外的异常被抛出,则执行这段代码

}【finally{

        //无条件执行的语句

}】

例子:

 

package org.example.面向对象;

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

public class Exp {
    public static void test(){
        try{
            int[] arr={1,2,3};
            System.out.println(arr[2]);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("finally");
        }
        System.out.println("--------------");
    }
    public static void test2(){
        FileInputStream fileInputStream=null;
        try{
            String filePath="D://a.txt";
            fileInputStream=new FileInputStream(filePath);
            byte[] bytes=new byte[1024];
            while (fileInputStream.read(bytes)!=-1){

            }
            fileInputStream.close();
        }catch (FileNotFoundException e){
            e.printStackTrace();
            System.out.println("------------------");
        }catch (IOException e){
            e.printStackTrace();
            System.out.println("--------------------");
        }finally {
            System.out.println("finally");
        }
    }
    public static void main(String[] args){
        test();
        test2();
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

塔塔o

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值