-
异常分类
- 检查性异常:最具代表的检查性异常是用户错误或问题引起的异常,这是程序员无法预见的,在编译时不能被简单忽略
- 运行时异常:运行时异常是最可能被程序员避免的异常,在编译时可以被忽略
- 错误:错误不是异常,而是脱离程序员控制的问题,错误在代码中通常被忽略,在编译时检查不到
-
异常的体系结构
- Java把异常当作对象来处理,并定义了一个基类java.lang.Throwable作为所有异常的超类
- 在Java API中已经定义了许多异常类,这些异常类分为两大类,错误Error和异常Exception
- 常见的错误和异常:
-
异常处理机制
- 异常处理的五个关键字:try、catch、finally、throw、throws
- 捕获多个异常要从小到大进行捕获
public class Test{ public static void main(String[] args){ int a = 1; int b = 0; //IDEA快捷键 Ctrl + Alt + T try{ //try监控区域 System.out.println(a/b); }catch(Error e){ //catch(想要捕获的参数类型 命名)捕获异常 System.out.println("Error"); }catch(Exception e){ System.out.println("Exception"); }catch(Throwable t){ System.out.println("Throwable"); }finally{ //处理善后工作,释放资源,可以不要 System.out.println("这是finally"); } } } /*运行结果: Exception 这是finally*/
- 主动抛出异常
public class Test{ public static void main(String[] args){ new Test().test(1,0); } public void test(int a, int b){ if(b == 0){ try{ throw new ArithmeticException(); //主动抛出异常 }catch(ArithmeticException e){ e.printStackTrace(); } } System.out.println(a/b); } }
- 方法上抛出异常
public class Test{ public static void main(String[] args){ try{ new Test().test(1,0); //调用该方法时捕获异常 }catch(ArithmeticException e){ e.printStackTrace(); } } //假设方法中处理不了这个异常,就在方法上抛出异常 public void test(int a, int b) throws ArithmeticException{ if(b == 0){ throw new ArithmeticException(); } System.out.println(a/b); } }
-
自定义异常
- 使用Java中内置的异常类可以描述在编程中出现的大部分异常问题。除此之外,用户可以自定义异常,只需要继承Exception类即可
- 自定义异常类的步骤:
- 创建自定义异常类
- 在方法中通过throw关键字抛出异常对象
- 如果在当前抛出异常的方法中处理异常,可以使用try-catch语句捕获并处理;否则在方法的声明处通过throws关键字指明要抛出给方法调用者的异常,继续进行下一步操作
- 在出现方法的调用者中捕获并处理异常
//自定义的异常类 public class MyException extends Exception{ //传递信息 private String message; public MyException(String message){ this.message = message; } //toString打印异常信息 @Override public String toString(){ return "MyException{" + message+ "}"; } } public class Test{ public void test(int a, int b) throws MyException{ if(b == 0){ String message = "被除数不能为0"; throw new MyException(message); } System.out.println(a/b); } public static void main(String[] args){ try{ new Test().test(1,0); }catch(MyException e){ System.out.println("MyException => " + e); //MyException => MyException{被除数不能为0} } } }
异常
最新推荐文章于 2024-10-01 18:51:18 发布