java的基本异常处理

一、异常的分类:
Throwable包含了错误(Error)和异常(Excetion两类)
在这里插入图片描述
1.Error是程序无法处理了, 如果OutOfMemoryError、OutOfMemoryError等等, 这些异常发生时, java虚拟机一般会终止线程。
2 .运行时异常都是RuntimeException类及其子类,如 NullPointerException、IndexOutOfBoundsException等, 这些异常是不检查的异常, 是在程序运行的时候可能会发生的, 所以程序可以捕捉, 也可以不捕捉. 这些错误一般是由程序的逻辑错误引起的, 程序应该从逻辑角度去尽量避免。
3检查异常是运行时异常以外的异常, 也是Exception及其子类, 这些异常从程序的角度来说是必须经过捕捉检查处理的, 否则不能通过编译. 如IOException、SQLException等。

关于运行异常的代码
1 .可以捕获多个异常

public class Test {
    public static void main(String[] args) {
        int a=10;
        int b=0;
//        System.out.println(a/b);
        try {//监控区
            System.out.println(a/b);
        }catch (ArithmeticException e){//catch(需要捕获的异常类型) 捕获异常
            System.out.println("程序出现错误除数不为0");
        }
        catch (Error e){
            System.out.println("Error");
        }
        catch (Exception e){
            System.out.println("Exception");
        }
        catch (Throwable e){
            System.out.println("Throwable");
        }
        finally {
            System.out.println("处理善后");
        }
    }
}

2.快捷键

//快捷键Ctrl+alt+T
public class Test2 {
    public static void main(String[] args) {
      int a=1;
      int b=0;
        try {
            System.out.println(a/b);
        } catch (Exception e) {
            e.printStackTrace();//打印系统报的错误
//            public void printStackTrace() {
//                printStackTrace(System.err);
//            }
        } finally {
            System.out.println("Ctrl+alt+T");
        }
    }
}

3. throw 和 throws

public class Test3 {
    public static void main(String[] args) {
        try {
            new Test3().test(1,0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
//    假设方法中处理不了这个异常,就在方法上抛出异常 用了这个要捕获
    public void  test(int a,int b)throws Exception {
        if(b==0){
            throw  new ArithmeticException();//主动抛出异常,一般在方法中使用
        }
        System.out.println(a/b);
    }
}

4补充自定以异常

public class MyException extends Exception {
//     传递数字>10,大于10的异常
    private int num;
    public MyException(int a) {
        this.num = a;
    }
//    toString打印出 可以用alt+insert选择toString()
    @Override
    public String toString() {
        return "MyException{" +
                "num=" + num +"自定义异常"+
                '}';
    }
}

调用这个异常

public class Test {
    //    可能存在异常的方法   直接抛出
    public void test(int a) throws MyException {
        if (a > 10) {
            throw new MyException(a);
        }
        System.out.println("OK");
    }

    public static void main(String[] args) {
        try {
            new Test().test(11);
        } catch (MyException e) {
//            可以增加处理异常的代码块
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值