异常
异常
- Throwable
package oop.demo07;public class Test { public static void main(String[] args) { int a = 1; int b = 0; //假设要捕获多个异常:从小到大! new Test().test(1,0); try{ //try监控区域 new Test().a(); System.out.println("a/b"); }catch (Error e){ System.out.println("E"); }catch (Exception e){ System.out.println("E"); }catch (Throwable t){ System.out.println("T"); }finally { //处理善后 System.out.println("F"); } } public void a(){ b(); } public void b(){ a(); } public void test(int a,int b){ if (b==0){ throw new ArithmeticException(); //主动抛出异常(一般在方法中使用) } }}
MyException
package oop.demo07;public class MyException extends Exception{ private int detail; public MyException(int a) { this.detail = a; } //toString异常的打印信息 @Override public String toString() { return "MyException{" + detail + '}'; }}
package oop.demo07;public class Test02 { static void test(int a) throws MyException { System.out.println("传递参数为:"+ a ); if (a>10){ throw new MyException(a); } System.out.println("OK"); } public static void main(String[] args) { try { test(1); } catch (MyException e) { System.out.println("MyException=>"+e); } }}