异常处理Exception

Day10 Java

**

一.异常处理的模板**

/**

  • 异常处理 处理运行过程中出现的不可控的错误:error 是程序更健壮
    *Exception1- 处理模式
  • try{
  • 执行的代码
    
  • 可能出现异常
    
  • 一旦出现异常 系统自动为我们创建一个异常对象 并抛出
    
  • }catch(NullPointerException e){
  • 如果需要自己处理异常就catch
    
  • }catch(IOException e){
  • 如果有多个异常 可以使用多个catch来捕获
    
  • 如果有多个异常 catch 的顺序从小到大
    
  • }catch(Exception1 e){
  • }finally{
  •  不管有没有异常finally 都会被执行
    
  • 处理资源会收  网络连接 数据库连接 I/O流
    
  • }

二.主要的方法***

1.try.

  • 如果异常出现 后面的代码不执行
  • *try 代码块 不要抓太多代码
  • 2.使用throws抛出异常 给外部处理
  • 3.当特殊情况出现 自己可以选择抛出异常
  • throw
  • 4.自定义异常类

三.代码*实际例子

public class Exception1 {
    public static void main(String[] args){
        int a = 0;
        int b = 20;
        //  int c = b/a;  //❌
        FileReader fr = null;
        try{
            int c = b/a;
            System.out.println("Hello");  //没有执行 上面已经异常 
            fr = new FileReader("");
        }catch (ArithmeticException e){
            System.out.println(e.getMessage());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            try {
                fr.close();
            }catch (IOException i){

            }
        }


        //()里面只能添加可以关闭的对象 不需要写finally 自动释放
        //实现了Closeable接口的对象
        //优点:如果出现异常 系统自动关闭这个资源
        try(FileReader fr1 = new FileReader("dddd")){

        }  catch (IOException e) {
            e.printStackTrace();
        }

        //谁来调用谁来处理
        try {
            TException.test();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        System.out.println("______________________");
        try{
            TException.test3();
        }catch (GSException e){
            System.out.println(e.getMessage());
        }
    }

}

//到底谁来处理异常
class  TException{
    public static void test() throws FileNotFoundException,NullPointerException{
        FileReader fr = new FileReader("");
    }

    //自己去抛
    public static void test2()throws  IllegalAccessException{
        //.....
        if (8 > 9){
            throw  new IllegalAccessException();
        }
    }
    public  static void test3()throws GSException{
        //....
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        StackTraceElement e = stackTrace[2];
        String details = e.getFileName()+"->"e.getMethodName()+"->"e.getLineNumber();
        throw  new GSException("自己的异常类:无所作为"+details);
    }
}

//自己写的
class GSException extends Exception{

    //1.提供一个无参构造方法
    public GSException(){

    }

    //2.提供一个有参构造方法 参数是一个字符串
    public GSException(String decri){
        super(decri);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值