Java异常处理程序未捕获异常示例

原创 Bertha 。 2024-12-01 02:27 125阅读 0赞

在Java中,当一个方法或者代码块抛出一个未被捕获的异常时,系统会默认这个异常会被最上层的try-catch结构捕获。

以下是一个未捕获异常的示例:

  1. public class UncaughtExceptionExample {
  2. public static void main(String[] args) {
  3. // 方法可能会抛出未被捕获的异常
  4. throwNewException();
  5. }
  6. // 自定义方法,模拟可能抛出异常的情况
  7. private static void throwNewException() {
  8. try {
  9. // 这里代码可能导致异常,但没有捕获
  10. int divideByZero = 10 / 0;
  11. System.out.println("This should not print since division by zero is an error.");
  12. } catch (ArithmeticException e) {
  13. // 这里是故意捕获这个未被捕获的异常
  14. System.out.println("Caught the exception: " + e.getMessage());
  15. }
  16. }
  17. }

在这个示例中,throwNewException() 方法可能会抛出一个 ArithmeticException,但我们在方法体内部没有捕获这个异常。因此,当运行程序时,尽管出现了异常,但我们故意在catch块中捕获了它,从而避免了未捕获异常的情况。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,125人围观)

还没有评论,来说两句吧...

相关阅读