五个关键词
package Exception.Demo01;//异常处理机制//抛出异常//捕获异常//关键词:try\catch\finally\throw\throwspublic class Demo01 { public static void main(String[] args) { int a = 10; int b = 0;// try{//try监控区域// System.out.println(a/b);// }catch (ArithmeticException e){//捕获异常// System.out.println("程序出现异常,变量b不能为0");// }finally {//程序无论有无异常,finally都会执行,finally不是必须,一般处理善后工作// System.out.println("finally");// } //要捕获多个异常,要从小到大地捕获 try{//try监控区域 System.out.println(a/b); }catch (Error e){ } catch (Exception e){//捕获异常 System.out.println("程序出现异常,变量b不能为0"); } catch (Throwable e){ } finally {//程序无论有无异常,finally都会执行,finally不是必须,一般处理善后工作 System.out.println("finally"); } }}
自定义异常
package Exception.Demo02;//自定义异常类public class MyException extends Exception{ //传递数字-->如果数字大于10,就抛出异常 private int detail; public MyException(int a){ this.detail = a; } //toString //fn+alt+insert @Override public String toString() { return "MyException{" + "detail=" + detail + '}'; }}
package Exception.Demo02;public class Test { //可能会存在异常的方法 static void test(int a) throws MyException{ if(a > 10) { throw new MyException(a); } System.out.println("OK"); } public static void main(String[] args) { try{ test(11); }catch (MyException e){ System.out.println("MYException"); } //MYException }}