对于在座的大多数人来说,这可能是一个非常愚蠢的问题,对此深表歉意。我是Java新手,而我正在阅读的书并未解释其中示例的工作原理。
public class CrazyWithZeros
{
public static void main(String[] args)
{
try
{
int answer = divideTheseNumbers(5, 0);
}
catch (Exception e)
{
System.out.println("Tried twice, "
+ "still didn't work!");
}
}
public static int divideTheseNumbers(int a, int b) throws Exception
{
int c;
try
{
c = a / b;
System.out.println("It worked!");
}
catch (Exception e)
{
System.out.println("Didn't work the first time.");
c = a / b;
System.out.println("It worked the second time!");
}
finally
{
System.out.println("Better clean up my mess.");
}
System.out.println("It worked after all.");
return c;
}
}
在
divideTheseNumbers()
方法的catch块中生成另一个异常之后,我无法弄清楚控件将去哪里?任何帮助将不胜感激 !
最佳答案
您程序的输出将是
Didn't work the first time.
Better clean up my mess.
Tried twice, still didn't work!
Didn't work the first time.
-由于divideTheseNumbers
中的catch块Better clean up my mess.
-由于divideTheseNumbers
中的finally块Tried twice, still didn't work!
-由于main
方法中的catch块。通常,从方法抛出异常并且如果不在
try
块中,则将其抛出给调用方法。有两点需要注意:
1)任何不在
try
块中的异常都将被抛出它正在调用方法(即使它在
catch
块中)2)
finally
块始终被执行。在您的情况下,您在
catch
块中获得了第二个异常,因此将引发该异常。但是在退出任何方法之前,它还将执行finally
块(最终总是执行块)。这就是为什么还要打印Better clean up my mess
的原因。