确定什么是已检查的,什么是考试条件中的未检查异常?

Determining what is Checked and what is an Unchecked Exception in Exam Conditions?

我正在备考 Java Associate 考试,我正在努力确定在考试条件下什么是选中的,什么是未选中的。我知道如果我可以根据我在此处阅读的内容编写代码,我可以查找它或执行 instanceof - 但是有没有一种简单的方法可以确定它。我选了一些,但发现很难全部记住。下面是一个依赖于这些知识的问题的考试。

public static String readData (Path filePath)
  throws IOException, IllegalArgumentException {
     //implementation omitted
}

将编译哪两个代码片段?

public static void main(String[] args) {
 try {
      readData(Paths.get("test"));
 } catch (IllegalArgumentException ex) {
      System.err.println(ex);
 }
}

public static void main(String[] args)
  throws IOException{
 readData(Paths.get("test.txt"));
}

public static void main(String[] args)
  throws IllegalArgumentException{
 readData(Paths.get("test.txt"));
}

public static void main(String[] args) {
 readData(Paths.get("test.txt"));
}

public static void main(String[] args) {
try {
 readData(Paths.get("test"));
 } catch (IOException ex) {
      System.err.println(ex);
 }
}

Checked Exceptions 是在编译时检查的异常。如果方法中的某些代码抛出已检查的异常,则该方法必须处理该异常,或者必须使用 throws 关键字指定该异常。 某些异常,如 FileNotFoundException(IOException 的子 class)被检查为异常,应在代码中处理。

Unchecked是编译时不检查的异常。 在 Java Error 和 RuntimeException class 下的异常是未经检查的异常,所有其他在 throwable 下的都被检查。

所以对于你给出的问题,IOException 是一个已检查的异常,而 IllegalArgumentException 是一个未检查的异常。 答案是:第二个选项和最后一个选项

Correct Answers: 
public static void main(String[] args)
  throws IOException{
 readData(Paths.get("test.txt"));
}

public static void main(String[] args) {
try {
 readData(Paths.get("test"));
 } catch (IOException ex) {
      System.err.println(ex);
 }
}

所以,对于任何发现它被选中或未被选中的异常,你可以像 如果由于任何用户输入或编译时未知的任何其他外部值而发生异常,则将取消选中。其他异常检查Exceptions

例如,IllegalArgumentException,如果参数是非法的。您在编写代码时不知道参数,这不是预期的。所以,这是一个未经检查的异常。

您可以将上述规则应用于此列表中的所有异常

未选中

ArrayIndexOutOfBoundsException

ClassCastException

IllegalArgumentException

IllegalStateException

NullPointerException

NumberFormatException

断言错误

ExceptionInInitializerError

WhosebugError

NoClassDefFoundError