Java的异常处理
-
常见异常
① 运行时异常
a、ClassNotFoundException
b、FileNotFoundException
c、IOException
② 编译时异常
a、ArrayIndexOutOfBoundsException
b、NullPointerException
c、ClassCastException
d、InputFormatException
e、InputMismatchException
f、ArithmeticException -
try-catch-finally(抓抛模型)
① 抛:程序在执行的过程当中,一旦出现异常,就会在出现异常的代码处,生成对应异常类的对象,并将此对象抛出。
② 抓:针对于上方抛出的异常对象,进行捕获处理。
③ 语法格式try {}catch(NullPointerException e) {e.printStackTrace(); // 打印异常信息 }catch(InputMismatchException e) {System.out.println(e.getMessage()); } ... finally { }
-
throws方式
向上抛出异常,延后处理// 测试方法 public void test() {// 在调用时处理异常try {method();}catch(Exception e) {} } public void method() throws 异常1,异常2{...}
-
说明
① 子类重写的方法抛出的异常类型可以与父类被重写的方法抛出的异常相同,或是父类被重写的方法抛出的异常类型的子类。 -
手动抛出异常
class Student {int id;public void setId(int id) throws Exception {if (id > 0) {this.id = id;} else {// 手动抛出异常throw new Exception("输入格式错误");}} } public class Test {public static void main(String[] args) {try {Student s = new Student();s.setId(-5);} catch(Exception e) {System.out.println(e.getMessage()); // 打印异常message -> 输入格式错误e.printStackTrace(); // 打印异常详细信息}} }
-
自定义异常
① 继承现有异常类(RuntimeException,Exception)
② 依照父类,提供几个重载构造器
③ 提供全局常量,static final long serialVersionID;//自定义TestException异常类 class TestException extends Exception {static final long serialVersionUID = 123123123L;public testException() {super();}public testException(String message) {super(message);}public testException(String message, Throwable cause) {super(message, cause);} } public class Test {public static void main(String[] args) {try{method();} catch(TestException e) {e.printStackTrace();}}public static void method() throws TestException {setTimeout(() => {throw new TestException("错误消息");}, 5000);} }