finally 什么情况不会被执行?
try{}
catch(Exception e){
System.exit(0);
}
finally{}
神马?上面的finally不会被执行?你确定?往下看:
try{
throw new Exception("异常了!");
}
catch(Exception e){
System.exit(0);
}
finally{}
即当 try 中发生异常,且被catch 捕获,catch 块中有 System.exit(0); 语句时JVM提前退出了;也就没有 finally 神马事情了;
补充(一):try catch finally 结合的几种方式:
//1、
try{}
catch(Exception e){}
//2、
try{}
finally{}
//3、
try{}
catch(Exception e){}
finally{}
Exception(一)
//1、
public class ExceptionTest{
public static void main(String[] args){
ExceptionTest et = new ExceptionTest();
et.exceptionMeth();
}
public void exceptionMeth() {
throw new RuntimeException("runtimeException!");
}
}
//2、
public class ExceptionTest{
public static void main(String[] args){
ExceptionTest et = new ExceptionTest();
try{
et.exceptionMeth();
}catch(Exception e){}
}
public void exceptionMeth() {
throw new Exception("Exception!");
}
}
问:上面两段代码编译结果是神马?
答:代码1 编译通过,RuntimeException不会被编译器检查;
代码2 编译失败,Exception 要么被catch,要么被throws。
Exception(二)
class ExceptionTest{
public static void main(String[] args){
try{
func();
System.out.println("A");
}catch(Exception e){
System.out.println("C");
}
System.out.println("D");
}
public static void func()throws Exception{
try{
throw new Exception();
}finally{
System.out.println("B");
}
}
}
问:上面程序输出结果是神马?
答:
B
C
D
A 不会被输出, 因为 func()抛出异常,会进入catch块中
Exception(三)
下面代码执行结果是:
class FatherException extends Exception{}
class ChildException extends FatherException {}
class ExceptionTest{
public static void main(String[] args){
try{
throw new ChildException();
}catch(FatherException e){
System.out.println("FatherException !");
}catch(ChildException e){
System.out.println("ChildException !");
}catch(Exception e){
System.out.println("Exception !");
}
System.out.println("D");
}
}
问:上面代码输出神马?
编译失败 : 多个catch时,父类型异常的catch不可以出现在子类型异常catch之前。
Exception(四)
class Demo{
public static void func(){
try{
throw new Exception();
System.out.println("A");
}catch(Exception e){
System.out.println("B");
}
}
public static void main(String[] args){
try{
func();
}catch(Exception e){
System.out.println("C");
}
System.out.println("D");
}
}
结果:编译失败;
注意:在同一语句块中,throw,return,break之后不要再有其他语句;因为永远不可能执行到;