一:基本概念
当程序中出现了某些“错误”,但该错误信息并没有在Throwable子类中描述处理,这个时候可以自己设计异常类,用于描述该错误信息。
二:自定义异常的步骤
- 定义类:自定义异常类名(程序员自己写)继承Exception或RuntimeException
- 如果继承类Exception,属于编译异常
如果继承RuntimeException,属于运行异常(一般来说,继承RuntimeException)
三:自定义异常的应用实例
当我们接收Person对象年龄时,要求范围在18-120之间,否则抛出一个自定义异常(要求继承RuntimeException),并给出提示信息。 ```java public class Test2 { public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);int Age = scanner.nextInt();if (!(Age >=18 && Age <=120)){throw new Person("年龄需要在18-20之间");}System.out.println("年龄范围正确");
} } //自定义异常 //1. 一般情况下,我们自定义异常是继承 RuntimeException //2. 即把自定义异常做成 运行时异常,好处时,我们可以使用默认的处理机制 class Person extends RuntimeException{ public Person(String message) {
super(message);
} }
<a name="CUX8A"></a>### 四:throw和throws区别<a name="sQlfy"></a>### 五:练习:::info**_分层处理异常思想_**:::```javapublic class Test1 {public static void main(String[] args) {try {//先验证传入的个数if(args.length !=2){throw new ArrayIndexOutOfBoundsException("参数个数不对");}//再验证是否为整数double n1 = Integer.parseInt(args[0]);double n2 = Integer.parseInt(args[1]);//再验证算数异常double result = Cal(n1,n2);System.out.println("计算结果为:"+ result);}catch (ArrayIndexOutOfBoundsException e) {System.out.println(e.getMessage());}catch (NumberFormatException e){System.out.println("参数格式不正确");}catch (ArithmeticException e){System.out.println("算数异常");}}public static double Cal(double n1 ,double n2){return n1 / n2;}}
:::info
抛出异常之后,后面的代码块不在执行
如果有 throw或者return finally才会优先输出
:::

