try {
执行的代码,其中可能有异常。一旦发现异常,则当即跳到catch执行。不然不会执行catch里面的内容
} catch (Exception e) {
除非try里面执行代码发生了异常,不然这里的代码不会执行
}spa
finally {
无论什么状况都会执行,包括try catch 里面用了return ,能够理解为只要执行了try或者catch,就必定会执行 finally
}code
看下面题目对比:blog
1 public class test1 { 2 public static String output=""; 3 public static void foo(int i) { 4 try { 5 if(i==1) //throw new Exception("i不能为1"); 6 output+="A"; 7 } catch (Exception e) { 8 System.out.println(e.getMessage()); 9 output+="M"; 10 return; 11 }finally { 12 output+="C"; 13 } 14 output+="G"; 15 16 } 17 public static void main(String[] args) { 18 foo(0); 19 foo(1); 20 System.out.println(output); 21 } 22 }
结果为:get
CGACGio
1 public class test1 { 2 public static String output=""; 3 public static void foo(int i) { 4 try { 5 6 } catch (Exception e) { 7 // TODO: handle exception 8 }finally { 9 10 } 11 try { 12 if(i==1) throw new Exception("i不能为1"); 13 output+="A"; 14 } catch (Exception e) { 15 System.out.println(e.getMessage()); 16 output+="M"; 17 return; 18 }finally { 19 output+="C"; 20 } 21 output+="G"; 22 23 } 24 public static void main(String[] args) { 25 foo(0); 26 foo(1); 27 System.out.println(output); 28 } 29 30 }
结果为:class
i不能为1
ACGMCtest
throws:用于声明异常,例如,若是一个方法里面不想有任何的异常处理,则在没有任何代码进行异常处理的时候,必须对这个方法进行声明有可能产生的全部异常(其实就是,不想本身处理,那就交给别人吧,告诉别人我会出现什么异常,报本身的错,让别人处理去吧)。格式是:方法名(参数)throws 异常类1,异常类2,.....exception
1 class Math{ 2 public int div(int i,int j) throws Exception{ 3 int t=i/j; 4 return t; 5 } 6 } 7 8 public class ThrowsDemo { 9 public static void main(String args[]) throws Exception{ 10 Math m=new Math(); 11 System.out.println("出发操做:"+m.div(10,2)); 12 } 13 }
throw:就是本身进行异常处理,处理的时候有两种方式,要么本身捕获异常(也就是try catch进行捕捉),要么声明抛出一个异常(就是throws 异常~~)。程序
注意:方法
throw一旦进入被执行,程序当即会转入异常处理阶段,后面的语句就再也不执行,并且所在的方法再也不返回有意义的值!
public class TestThrow { public static void main(String[] args) { try { //调用带throws声明的方法,必须显式捕获该异常 //不然,必须在main方法中再次声明抛出 throwChecked(-3); } catch (Exception e) { System.out.println(e.getMessage()); } //调用抛出Runtime异常的方法既能够显式捕获该异常, //也可不理会该异常 throwRuntime(3); } public static void throwChecked(int a)throws Exception { if (a > 0) { //自行抛出Exception异常 //该代码必须处于try块里,或处于带throws声明的方法中 throw new Exception("a的值大于0,不符合要求"); } } public static void throwRuntime(int a) { if (a > 0) { //自行抛出RuntimeException异常,既能够显式捕获该异常 //也可彻底不理会该异常,把该异常交给该方法调用者处理 throw new RuntimeException("a的值大于0,不符合要求"); } } }