概述
异常是一些用来封装错误信息的对象
它由异常的类型、提示信息、报错的行号提示三部分组成
异常继承结构
Throwable:顶级父类
- Error:系统错误,无法修复
- Exception:可以修复的错误
- RunTimeException:编译错误
- IndexOutOfBoundsException—数组下标越界
- InputMismatchException—输入不匹配
- ArithmeticException—算数异常
- ClassCastException
- ClassNotFoundException
- RunTimeException:编译错误
异常处理方式
当程序中遇到了异常,通常有两种处理方式:捕获或者向上抛出
当一个方法抛出异常,调用位置可以不做处理继续向上抛出,也可以捕获处理异常捕获方式
捕获异常的方式try{可能会出现异常的代码}catch(异常类型 类型名){捕获到异常进行处理解决的方法}
抛出方式
修饰符 返回值类型 方法名(参数列表) throws 异常类型 {方法体;}
示例
```java package cn.tedu.Exception;
import java.util.InputMismatchException; import java.util.Scanner;
/**
- 异常入门案例 */
public class TestException { public static void main(String[] args) { //f1(); //f2(); //f3(); method(); }
private static void method() {try {f3();} catch (Exception e) {System.out.println("输入数据有误");}}/*异常抛出格式:在小括号和大括号之间写:throws 异常类型如果一个方法抛出了异常,谁调用这个方法,谁就需要处理这个异常处理有两种方案:捕获解决和继续向上抛出注意:一般需要在main()方法调用之前解决异常,而不是把问题交给main方法,这样将会导致无人解决异常*/private static void f3() throws ArithmeticException,InputMismatchException,Exception{System.out.print("请输入被除数:");int a = new Scanner(System.in).nextInt();System.out.print("请输入除数:");int b = new Scanner(System.in).nextInt();System.out.println("计算结果为:" + a/b);}/*捕获异常的方式try{可能会出现异常的代码}catch(异常类型 类型名){捕获到异常进行处理解决的方法}try-catch可以嵌套的,如果有多种异常类型需要分别处理如果不需要特殊处理,只需要处理,不需要嵌套将所有异常的子类型同意看作父类的Exception来处理提供一种通用的解决方法,这是多态最为经典的一种用法*/private static void f2() {try {System.out.print("请输入被除数:");int a = new Scanner(System.in).nextInt();System.out.print("请输入除数:");int b = new Scanner(System.in).nextInt();System.out.println("计算结果为:" + a/b);}catch (ArithmeticException e){System.out.println("0不可做除数");}catch (InputMismatchException e){System.out.println("输入类型有误,请输入整数类型");}catch (Exception e){System.out.println("请输入正确的数据!");}}private static void f1() {System.out.print("请输入被除数:");int a = new Scanner(System.in).nextInt();System.out.print("请输入除数:");int b = new Scanner(System.in).nextInt();System.out.println("计算结果为:" + a/b);//输入6与0报错ArithmeticException,原因除数不能为0//输入3与4.4报错InputMismatchException,原因输入类型不是int类型}
} ```
