标签:style c class blog code java
异常:编译正常,但运行出错,会中断正常指令流
RuntimeException:运行时异常
分为:uncheck exception、和check exception(除了RuntimeException以及子类以外的)
uncheck exception
class Test { public static void main(String args[]){ System.out.println("1"); int i = 1/0; System.out.println("2"); } }
异常处理:uncheck exception,try里面出异常,就跳到catch里面执行
try{..}
catch(){..}
finally{..}
class Test { public static void main(String args[]){ try{ int i = 1/0; }catch(Exception e){ //出异常执行这里 e.printStackTrace(); System.out.println("2"); }finally{ //不管出不出异常都执行这里 System.out.println("3"); } } }
throw抛出异常对象:
class User { void setage(int age){ if(age<0){ RuntimeException r = new RuntimeException("年龄不为负"); throw r; } System.out.println("函数末"); } }
class Test { public static void main(String args[]){ User u = new User(); u.setage(-3); } }
throws声明一个函数有可能产生异常,调用的时候再处理异常
class User { void setage(int age) throws Exception{ if(age<0){ Exception e = new Exception("年龄不为负"); throw e; } } }
class Test { public static void main(String args[]){ User u = new User(); try{ u.setage(-3); }catch(Exception e){ System.out.println(e); } } }
标签:style c class blog code java
原文地址:http://www.cnblogs.com/tinyphp/p/3740820.html