异常的简单概括
异常(Exception)
抛出异常
-
try监控区域,catch捕获异常,finally最终处理善后工作
-
ctrl alt T 自动生成
-
throw主动抛出异常,一般在方法中使用
-
throws定义方法时使用
try { student.test(name); }catch (Exception e){ }finally { }//主动抛出异常 public void test (){ if(){ throw new Exception(); } }public class Application { public static void main(String[] args) { //try catch进行捕获 try { test2(3); } catch (Exception e) { e.printStackTrace(); } } //方法主动抛出无法处理的异常 public static void test2(int a) throws Exception{ System.out.println(a); } }
自定义异常
-
必须继承Exception类
//异常类 public class MyEx extends Exception{ //传递数字>10 异常 private int detail; public MyEx(int a){ this.detail=a; } @Override public String toString() { return "MyEx{" + "detail=" + detail + '}'; } }//异常方法 static void test3(int a) throws MyEx{ if (a>10){ throw new MyEx(a); } }//捕获异常 public static void main(String[] args) { try { test3(12); } catch (MyEx e) { System.out.println(e); } }

浙公网安备 33010602011771号