异常类

Throwable中的方法

 getMessage():获取异常信息,返回字符串。
 toString():获取异常类名和异常信息,返回字符串。
 printStackTrace():获取异常类名和异常信息,以及异常出现在程序中的位置。返回值void。
 printStackTrace(PrintStream s):通常用该方法将异常内容保存在日志文件中,以便查阅。

所以呢,我们就得出一下结论:

  • 编译期异常抛出,将来调用者必须处理。
  • 运行期异常抛出,将来调用可以不用处理。

多个异常的处理

 
    public static void methods() {
        int a = 10;
        int b = 0;
        int[] arr = { 1, 2, 3 };

        try {
            System.out.println(a / b);
            System.out.println(arr[3]);
            System.out.println("这里出现了一个异常");
        } catch (ArithmeticException e) {
            System.out.println("除数不能为0");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("你访问了不该的访问的索引");
        } catch (Exception e) {
            System.out.println("出问题了");
        }

        System.out.println("over");
    }

运行期异常的抛出

    public static void method2() throws ArithmeticException {
        int a = 10;
        int b = 0;
        System.out.println(a / b);
    }

自定义异常类

class MyException extends Exception {
    public  MyException() {
    }
    public MyException(String message) {
        super(message);
    }
}

class Teacher16 {
    public void check(int score) throws MyException {
        if (score > 100 || score < 0) {
            throw  new  MyException("分数必须在0-100之间");
        }else  {
            System.out.println("分数没有问题");
        }
    }
}

你可能感兴趣的:(异常类)