2021.9.1异常处理

异常处理

异常(Exception)

  • 无法预测
  • 用户使用异常

错误(ERROR)

  • 大多是JVM异常

捕捉异常

public class 捕捉异常 {
    public static void main(String[] args) {

         //出现异常后面的就不执行了
        /*System.out.println("==========未处理异常==========");
        System.out.println(10/0);
*/

        System.out.println("==========已处理异常==========");
        try {//try监控区

            //放入执行代码
            System.out.println(10/0);
        } catch (Error e) {
            //系统错误
            System.out.println("Error");
        }
        catch (Exception e){
            //放入捕捉到异常后执行的语句
            e.printStackTrace();//输出系统栈异常
            System.out.println("Exception");

        }
        catch (Throwable t){
            System.out.println("异常");
            //可以写多个catch捕捉异常类型,Throwable,是所有异常捕捉,只能放在最后一个catch里
            System.out.println("Throwable");
        }finally
        {
            //默认执行,可以写入io.close ....关闭语句
            System.out.println("finally");
            System.exit(1);//关闭从程序
        }


    }
}

抛出异常

public class 抛出异常 {
    public static void main(String[] args) {
        int b = 0;

        //抛出后可继续执行
        try {
            if (b == 0) {
                throw new ArithmeticException();//主动抛出异常,一般在方法中使用
            }
        } catch (Exception e) {

        }

      //匿名对象
        new 抛出异常().ff(1,0);

    }

    public void ff(int a, int b) throws ArithmeticException {//方法异常的抛出
        if (b == 0) {
            throw new ArithmeticException();
        }

    }
}

自定义异常

//自定义异常类
public class 自定义异常 extends Exception{
   private int detail;

    public 自定义异常(int detail) {
        this.detail=detail;

    }

    @Override
    public String toString() {
        return "自定义异常{" +
                "detail=" + detail +
                '}';
    }
}

//==========运行测试=========
public class Test {
    //方法
    static void test(int a)throws 自定义异常{
        System.out.println("传递的参数:"+a);
        if (a>10){
            throw new 自定义异常(a);//抛出
        }
        System.out.println("OK");
    }

    //main入口
    public static void main(String[] args) {
        try {
            test(11);
        }catch (自定义异常 e){
            System.out.println("自定义异常>>>>>>"+e);
        }
    }




}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值