有人可以帮助我了解 java 中 try-catch 块的工作原理吗?

Can someone help me understand the working of try-catch block in java?

对于在座的大多数人来说,这可能是一个非常愚蠢的问题,对此深表歉意。我是 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 块中,它将被抛给它的调用方法。

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 a catch block)

2) finally block is always executed.

在你的例子中,你在 catch 块中得到第二个异常,所以它会被抛出。但是在退出任何方法之前它也会执行 finally 块(finally 块总是被执行)。这就是 Better clean up my mess 也被打印出来的原因。

关于异常处理的几点:

1. 将可能导致异常的代码放在 try{} 块中。
2. 使用 catch 块捕获适当的异常。
3. 在捕获异常时最好使用更具体的类型异常而不是捕获通用异常。例如,您捕获了 Exception,在这种情况下,您可能会捕获更具体的类型异常 ArithmeticException.
4. finally 块始终执行,即使您在 catchtry 块中使用 return 语句。
5. 方法 throwscatch 异常。如果方法 catch 异常,则不需要 throws 异常。
6.所有异常都不需要用catch-block处理。我们可以避免 unchecked exception 的 try-catch 块,例如 - ArithmeticExceptionNullPointerExceptionArrayIndexOutOfBoundsException。有关更多信息,请参阅 here

您还可以查看教程以了解有关 exception handling 的更多信息。