Java中异常处理:未捕获异常示例
在Java中,异常是一种错误情况的表示。如果在代码执行过程中发生了异常,但没有被捕获并进行适当的处理,那么这些未捕获的异常会在程序运行结束时被系统自动记录。
下面是一个简单的例子,展示了如何编写一个可能会抛出异常的函数,并尝试调用这个函数而没有捕获异常:
public class ExceptionExample {
public void division() throws Exception {
int numerator = 10;
int denominator = 0; // This will cause an exception
if (denominator != 0) {
double result = (double) numerator / denominator;
System.out.println("Division result: " + result);
} else {
throw new IllegalArgumentException("Cannot divide by zero!");
}
}
public static void main(String[] args) {
ExceptionExample example = new ExceptionExample();
try {
example.division(); // This line will throw an exception if not caught
} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
在这个例子中,division()
方法尝试进行除法运算,但当它试图除以零时(denominator = 0;
),Java会抛出一个 ArithmeticException
。在主函数中,我们调用 example.division();
并捕获任何可能的异常。如果未捕获异常,程序将会中断并显示错误信息。
还没有评论,来说两句吧...