异常机制

异常概念

异常处理机制

  • 抛出异常
  • 捕获异常
  • 异常处理五个关键字

    • try catch finally throw throws
  1. package exception;
  2. public class Test {
  3. public static void main(String[] args) {
  4. int a=1;
  5. int b=0;
  6. //假设要捕获多个异常,要从小到大去捕获
  7. try{//try监控区域
  8. System.out.println(a/b);
  9. }catch (ArithmeticException e){//catch 捕获异常
  10. System.out.println("ArithmeticException");
  11. }catch (Exception e){
  12. System.out.println("Exception");
  13. }
  14. catch (Throwable e){
  15. System.out.println("Throwable");
  16. }
  17. finally {//处理善后工作
  18. System.out.println("finally");
  19. }
  20. }
  21. }

主动的抛出异常,一般在方法中使用。