java异常处理

发布于:2022-12-20 ⋅ 阅读:(330) ⋅ 点赞:(0)

异常

  1. 检查性异常:用户错误或问题引起的异常

  2. 运行时异常:可以在编译时被忽略

  3. 错误:错误

异常处理框架

package com.exception;
​
public class Test {
    public static void main(String[] args) {
​
        new Test().test(1,0);
​
    }
​
        //假设这个方法中,处理不了这个异常,方法上抛出异常
        public void test ( int a, int b) throws ArithmeticException{
            if (b == 0) { //throw throws
                throw new ArithmeticException();//主动抛出异常, 一般在方法中使用
​
            }
            System.out.println(a/b);
        }
​
}
/*
//假设要捕获多个异常:从小到大
    try{//try监控区域
​
​
        System.out.println(a/b);
    }catch (Error e){//catch(想要捕获的异常类型)捕获异常
        System.out.println("程序出现异常,变量b不能为0");
​
    } catch (Exception o){
        System.out.println("222");
    }
    catch (Throwable t){
        System.out.println("333");
    }finally {
        System.out.println("111");
    }
​
    //finally 可以不要finally, 假设IO,资源,关闭!
​
    }
    public void a(){
        b();
    }
    public void b(){
        a();
    }
​
 */

实际经验中的一些总结

  1. 运行时异常,合理规避,辅助try-catch处理

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

  3. 不确定代码+try-catch

  4. 尽可能处理异常,而不是简单的打印

  1. 异常处理,从实际出发

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


网站公告

今日签到

点亮在社区的每一天
去签到