finally语句后面的语句到底会不会执行,什么情况下会执行呢//代码换成注释后的输出也不理解- -
public class J_Test {
public static void mb_createException()
{
throw new ArrayIndexOutOfBoundsException();
}public static void mb_method()
{
try
{
mb_createException();
System.out.print("a");
}
catch (Exception e)//第二种做法:Exception换成ArithmeticException
{
System.err.print("b");
}
finally
{
System.out.print("c");
}
System.out.print("d");//为什么第二种做法的时候,这句没有被执行???
}
public static void main(String args[])
{
try
{
mb_method();
}
catch (ArithmeticException e)//第二种做法:ArithmeticException换成Exception
{
System.err.print('m');
}
finally
{
System.out.print('n');
}
System.out.print('x');
}
}
public class J_Test {
public static void mb_createException()
{
throw new ArrayIndexOutOfBoundsException();
}public static void mb_method()
{
try
{
mb_createException();
System.out.print("a");
}
catch (Exception e)//第二种做法:Exception换成ArithmeticException
{
System.err.print("b");
}
finally
{
System.out.print("c");
}
System.out.print("d");//为什么第二种做法的时候,这句没有被执行???
}
public static void main(String args[])
{
try
{
mb_method();
}
catch (ArithmeticException e)//第二种做法:ArithmeticException换成Exception
{
System.err.print('m');
}
finally
{
System.out.print('n');
}
System.out.print('x');
}
}
1)若try{}中没有抛出任何异常,则执行完finally{}之后,finally后边的语句会继续执行。
2)若try{}中抛出异常,且该异常被自己的catch子句捕获,则先执行相应的catch子句,然后再执行finally{},finally后边的语句会继续执行。
3)若try{}中抛出异常,且该异常没有被自己的catch子句捕获,则先执行finally{},然后该异常将继续向外抛出,此时,该finally后边的语句将不会得到执行。
第一种做法,catch接住异常,并把它吞掉,下面继续执行
第二种做法,catch没有接住异常,到finally执行完,异常就被抛出函数,所以finally后面的没有执行
* 1.main方法调用 mb_method()方法, mb_method()方法调用mb_createException时候抛出了一个异常,try将其捕获
* 执行catch中的语句打印"b"
* 2.执行finally语句执行c
* 3.跳出try代码块,执行输出d
* 4.mb_method方法结束,由于mb_method将异常处理掉了所有main捕获不到异常,但是还要走try中的finally语句打印输出
* n
* 5.跳出try打印输出x
* total :bcdnx 拥有你的b是用System.err.print("b");输出 所以错误输出显示在最后红色显示
* */
谁能解释下为什么err那个红色的输出位置会改变的啊?
麻烦知道的大牛们回答一下吧,万分感谢呐~~~
public static void mb_createException()
{
throw new ArrayIndexOutOfBoundsException();
}public static void mb_method()
{
try
{
mb_createException();
System.out.print("a");
}
catch (ArithmeticException e)//(Exception e)
{
System.err.print("b");
}
finally
{
System.out.print("c");
}
System.out.print("d");
}
public static void main(String args[])
{
try
{
mb_method();
}
catch (Exception e)//(ArithmeticException e)
{
System.err.print('m');
}
finally
{
System.out.print('n');
}
System.out.print('x');
}
}
2)若try{}中抛出异常,且该异常被自己的catch子句捕获,则先执行相应的catch子句,然后再执行finally{},finally后边的语句会继续执行。
3)若try{}中抛出异常,且该异常没有被自己的catch子句捕获,则先执行finally{},然后该异常将继续向外抛出,此时,该finally后边的语句将不会得到执行。
按照这个规则,你可以去查查你的程序,看你得异常到底是如何处理的?
为什么输出顺序不一样,还是米有人回答诶 很遗憾~ >_<!
cmnx
D:\>java J_Test
cmnx
D:\>java J_Test
cmnx
D:\>java J_Test
cmnx
D:\>java J_Test
cmnx
D:\>java J_Test
cmnx
D:\>java J_Test
cmnx
D:\>
可是输出顺序会变千真万确,cmnx的概率是最大的。多试几次,一定会出现不同输出的。
郁闷 问老师他总是推脱着不讲。俺继续去问= =。