Java异常

异常机制

异常体系结构

Java把异常当作对象来处理,并定义一个基类java.lang.Throwable作为所有异常的超类

Error通常是致命的错误,由JVM生成并抛出

Exception可以被程序处理

img

异常处理机制

 package com.exception;
 ​
 public class Test {
     public static void main(String[] args) {
         
         int a = 1;
         int b = 0;
 ​
         System.out.println(a/b);
     }
 }
 // 出现异常:ArthmeticException: / by zero
 package com.exception;
 ​
 public class Test {
     public static void main(String[] args) {
 ​
         int a = 1;
         int b = 0;
         int c = 0;
         
         //类似if else,可以有多个catch 有多个catch时,catch括号里的异常类型要从细分的到大的
         
         try{//try监控区域 代码块中的异常
             System.out.println(a/b);
 ​
         }catch (ArithmeticException e){//捕获异常
             //如果try里面的代码块出现了catch括号里的异常,就会执行catch代码块的内容
             System.out.println("程序出现异常,变量b不能为0");
         }finally{
             //无论程序是否出现异常,都会执行finally代码块 可以不要finally,必须要有try catch
             System.out.println("finally");
         }
         
         //捕获异常快捷键:选择需要监控的代码 ctrl+alt+t
         try {
             System.out.println(a/c);
         } catch (Exception e) {
               e.printStackTrace();  //打印错误的栈信息 把这个异常打印出来
         } finally {
         }
 ​
     }
 }
 ​
 package com.exception;
 ​
 public class Test2 {
     public static void main(String[] args) {
         //抛出异常
         try {
             new Test2().test(1,0);
         } catch (ArithmeticException e) {
             System.out.println("ArithmeticException");
         }
 ​
     }
     //方法上抛出异常
     public void test(int a, int b) throws ArithmeticException {
         if(b == 0) {
             throw new ArithmeticException();    //主动抛出异常,一般在方法里使用
         }
 ​
     }
 }
 ​

自定义异常

java给的异常其实已经够用了

 package com.exception.demo02;
 ​
 //继承异常类 就获得了一个自定义异常类
 public class MyException extends Exception {
 ​
     //传递数字 >10 报异常
     private int detail;
 ​
     public MyException(int a) {
         this.detail = a;
     }
 ​
     @Override
     public String toString() {
         return "MyException{" +
                 "detail=" + detail +
                 '}';
     }
 }
 ​
 package com.exception.demo02;
 ​
 public class Test {
     //创建一个可能会存在异常的方法
     static void test(int a) throws MyException {
         System.out.println("传递的参数为:"+a);
 ​
         if(a >10) {
             throw new MyException(a);
         }
         System.out.println("OK");
     }
     public static void main(String[] args) {
         try {
             test(11);
         } catch (MyException e) {
             System.out.println("MyException:"+e);
         }
     }
 ​
 }
 ​

总结

  • 处理运行时异常时,采用逻辑去合理规避同时辅助try-catch处理

  • 在多重catch块后面,可以加一个catch(Exception)来处理可能被遗漏的异常

  • 对于不确定的代码,也可以使用try-catch,处理潜在的异常

  • 切忌只是简单的调用printStackTrace()去打印输出

  • 尽量添加finally语句块去释放占用的资源

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值