1 //MyException
2 //继承Exception的类,即为 自定义的异常类
3 public class MyException extends Exception{
4 //传递数字>10,则报异常
5 private int detail;
6 //Alt+Insert 自动添加构造方法
7 public MyException(int a) {
8 this.detail = a;
9 }
10 //toString:异常的打印信息 快捷键:Alt+Insert :toString
11 @Override
12 public String toString() {
13 return "MyException{" +
14 "detail=" + detail +
15 '}';
16 }
17
18 }
19
20 //test
21 public class Test {
22 static void test(int a) throws MyException {
23 System.out.println("传递的参数为:" + a);
24 if (a > 10) {
25 throw new MyException(a);//抛出
26 }
27 System.out.println("OK");
28 }
29
30 public static void main(String[] args){
31 try {
32 test(11);
33 } catch (MyException e) {
34 System.out.println("MyException->"+e);
35 }
36 }
37
38 }