try块包含可能会抛出异常的代码,catch块捕获并处理特定类型的异常,finally块无论是否抛出异常都会执行。
public class TryCatchFinallyExample {
public static void main(String[] args) {
try {
// 尝试执行可能会抛出异常的代码
performOperation();
} catch (ArithmeticException e) {
// 如果发生算术异常,例如除以零,则捕获并处理它
System.out.println("An arithmetic error occurred: " + e.getMessage());
} catch (Exception e) {
// 捕获其他所有类型的异常
System.out.println("An unexpected error occurred: " + e.getMessage());
} finally {
// 无论是否抛出异常,都会执行finally块中的代码
System.out.println("This is always executed, regardless of an exception.");
}
}
public static void performOperation() throws ArithmeticException {
int result = 10 / 0; // 这里会抛出ArithmeticException
System.out.println("Result is: " + result);
}
}
在这个例子中:
try
块包含了可能会抛出异常的代码。在这个例子中,performOperation
方法可能会抛出ArithmeticException
。catch
块捕获并处理特定类型的异常。这里有两个catch
块:第一个专门处理ArithmeticException
,第二个处理所有其他类型的Exception
。finally
块无论是否抛出异常都会执行。在这个例子中,它用于打印一条消息,表明finally
块已经被执行。
这个结构确保了即使在发生异常的情况下,也能执行一些清理工作,比如关闭文件流、释放资源等。finally
块是可选的,但通常推荐使用,因为它提供了一种确保执行清理代码的方法。
Comments NOTHING