异常处理五个关键字
try(监控区域) catch(捕获异常) finally(始终执行) throw(方法体里面用) throws(方法名后面用)
public class demo4 { public static void main(String[] args) { int a = 1; int b = 0; //捕获异常 ,要从小到大的顺序捕获,否则程序报错 快捷键: 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 { //finally 处理善后工作 System.out.println("都会执行finally"); }
//finally 可以不要finally 假设IO,资源,关闭
public class demo4 { public static void main(String[] args) { new demo4().test(1,0); } public void test( int a,int b){ if(b==0){ throw new ArithmeticException();//主动抛出异常,在方法体用 } } }
public class demo4 { public static void main(String[] args) { try { new demo4().test(1, 0); } catch (ArithmeticException e) { e.printStackTrace(); } } //在方法名后面用throws 抛出异常 public void test(int a, int b) throws ArithmeticException { System.out.println(a/b); } }
浙公网安备 33010602011771号