对于这里的大多数人来说,这可能是一个非常愚蠢的问题,对此感到非常抱歉。我是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 block 中生成另一个异常后控件将转到哪里?
任何帮助将不胜感激!
最佳答案
您的程序的输出将为
Didn't work the first time.
Better clean up my mess.
Tried twice, still didn't work!
第一次不起作用。
- 由于 divideTheseNumbers
中的 catch block
更好地清理我的困惑。
- 因为divideTheseNumbers
尝试了两次,仍然不起作用!
- 因为 main
方法中的 catch block 。
一般来说,当方法抛出异常时,如果异常不在 try
block 中,则会将异常抛出到其调用方法。
There are two points to note :
1) Any exception that is not in a
try
block will be just thrown to it's calling method(even if it is in acatch
block)2)
finally
block is always executed.
在您的情况下,您在 catch
block 中收到第二个异常,因此它将被抛出。但在退出任何方法之前,它也会执行finally
block (finally block 总是被执行)。这就是为什么也会打印 Better clean up my bads
的原因。
关于java - 有人可以帮助我理解 java 中 try-catch block 的工作原理吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31640499/