Java异常处理:try-catch-finally语句应用实例
在Java编程中,异常处理是通过try-catch-finally结构来实现的。下面是一个简单的例子,演示如何使用这个结构:
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
// 有可能抛出异常的代码
int divisionByZero = 10 / 0; // 这会抛出ArithmeticException
// 如果try块中没有发生任何异常,那么下面的代码将会执行
System.out.println("Division by zero is not allowed, but result would be " + divisionByZero);
} catch (ArithmeticException e) { //捕获特定类型的异常
System.out.println("An error occurred while performing division: " + e.getMessage());
} finally {
System.out.println("This block always executes regardless of an exception being caught.");
}
}
}
在这个例子中,我们尝试执行一个会抛出ArithmeticException
的代码(除以零)。然后我们在catch
块中捕获这个特定类型的异常,并打印错误信息。在finally
块中,无论是否发生异常,都会执行一些清理工作。
还没有评论,来说两句吧...