Java异常处理机制与捕获异常示例
在Java编程中,异常处理机制是用来管理程序运行时可能出现的错误。主要通过try-catch-finally结构来实现。
下面是一个简单的捕获异常的例子:
public class ExceptionHandlingExample {
public static void main(String[] args) {
// 尝试执行可能会抛出异常的操作
try {
// 这里会抛出ArithmeticException,因为除数为0
int result = 10 / 0;
System.out.println("Normal division result: " + result);
} catch (ArithmeticException e) {
// 捕获到的异常
System.out.println("Error occurred: " + e.getMessage());
} finally {
// 这里无论是否发生异常,都会执行
System.out.println("This is the finally block, always executed.");
}
}
}
在这个例子中,我们尝试进行除法操作,但因为除数为0(10 / 0
),这会抛出一个ArithmeticException
。
我们使用try-catch
结构来捕获这个异常。在catch
块中,我们打印出了错误信息。
最后的finally
块无论是否发生异常,都会被执行。在这个例子中,它只是简单地输出一条语句。
还没有评论,来说两句吧...