当main方法抛出异常时,它意味着什么? [英] What does it mean when the main method throws an exception?

查看:332
本文介绍了当main方法抛出异常时,它意味着什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在审查我为明天上午的期末考试做准备的期中考试。我错了这个问题,但是没有正确的答案指出,我忽略了向教授询问它。

I'm reviewing a midterm I did in preparation for my final exam tomorrow morning. I got this question wrong, but there's no correct answer pointed out, and I neglected to ask the prof about it.

考虑以下代码片段:

public static void main(String[] args) throws FileNotFoundException

关于此代码的以下哪些陈述是正确的?

Which of the following statements about this code is correct?


  1. 主要方法旨在捕获处理所有类型的异常。

  2. main方法用于捕获和处理 FileNotFoundException

  3. 如果发生 FileNotFoundException ,主要方法应该终止。

  4. 如果发生任何异常,主方法应该终止。

  1. The main method is designed to catch and handle all types of exceptions.
  2. The main method is designed to catch and handle the FileNotFoundException.
  3. The main method should simply terminate if the FileNotFoundException occurs.
  4. The main method should simply terminate if any exception occurs.

我选择了第二个选项。

推荐答案

答案是4号,


4.-主要方法应该在发生任何异常时终止。

4.- The main method should simply terminate if any exception occurs.

throws子句仅声明该方法抛出已检查的FileNotFoundException,并且调用方法应该捕获或重新抛出它。如果在main方法中抛出(而不是catch)未检查的异常,它也将终止。

The throws clause only states that the method throws a checked FileNotFoundException and the calling method should catch or rethrow it. If a non-checked exception is thrown (and not catch) in the main method, it will also terminate.

检查此测试:

public class ExceptionThrownTest {

    @Test
    public void testingExceptions() {

        try {
            ExceptionThrownTest.main(new String[] {});
        } catch (Throwable e) {
            assertTrue(e instanceof RuntimeException);
        }

    }

    public static void main(String[] args) throws FileNotFoundException {

        dangerousMethod();

        // Won't be executed because RuntimeException thrown
        unreachableMethod();

    }

    private static void dangerousMethod() {
        throw new RuntimeException();
    }

    private static void unreachableMethod() {
        System.out.println("Won't execute");
    }
}

如你所见,如果我抛出 RuntimeException 即使抛出的异常不是 FileNotFoundException

As you can see, if I throw a RuntimeException the method will terminate even if the exception thrown is not a FileNotFoundException

这篇关于当main方法抛出异常时,它意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆