【问题标题】:Determining what is Checked and what is an Unchecked Exception in Exam Conditions?在考试条件中确定什么是已检查以及什么是未检查异常?
【发布时间】:2015-03-11 16:38:02
【问题描述】:

我正在为 Java 助理考试而学习,并且在考试条件下正在努力确定哪些是已检查的,哪些是未检查的。我知道如果我可以根据我在这里阅读的内容编写代码,我可以查找它或执行 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);
 }
}

【问题讨论】:

  • 我不认为有什么办法可以让你牢记RuntimeExceptions。但是有一些比其他更经常使用。标准的RuntimeExceptions 通常非常广泛,或者即使您不调用方法(NullPointerExceptionArrayIndexOutOfBoundsExceptionArithmeticException)也可能发生,检查异常往往更“专门”。 IE。 IOException 适用于 IO 上下文,但IllegalArgumentException 适用于传递给方法的参数无效时。

标签: java exception checked-exceptions


【解决方案1】:

Checked Exceptions 是在编译时检查的异常。如果方法中的某些代码抛出检查异常,则该方法必须要么处理异常,要么必须使用 throws 关键字指定异常。 一些像 FileNotFoundException(IOException 的子类)这样的异常是检查异常,应该在代码中处理。

未检查是在编译时未检查的异常。 在 Java 中,Error 和 RuntimeException 类下的异常是未经检查的异常,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);
 }
}

因此,对于任何发现它已选中或未选中的异常,您可以将其保留为 如果由于任何用户输入或在编译时未知的任何其他外部值而发生异常,则将取消选中。其他异常都是检查异常

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

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

未选中

ArrayIndexOutOfBoundsException

类转换异常

IllegalArgumentException

非法状态异常

空指针异常

数字格式异常

断言错误

ExceptionInInitializerError

堆栈溢出错误

NoClassDefFoundError

【讨论】:

  • 我再次理解了选中和未选中的含义,但是我如何在不记住所有内容的情况下确定哪个是哪个?有没有办法从名称中计算出检查的异常类型?
  • 因此,对于任何发现它被选中或未选中的异常,你可以保持它就像如果由于任何用户输入或任何其他在编译时未知的外部值而发生的异常将不加检查。其他异常检查异常
  • 抱歉,您能详细说明一下吗?给定示例 NoSuchMethodException。
  • 感谢您的帮助。我现在感觉有点自信了。我会离开并将你的推理应用于我的考试问题。
  • 为什么 IOException 和 Checked Exceptions 放在一起?难道它不是用户输入的结果,因此在编译时不知道,因此应该取消选中?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-13
  • 2016-10-16
  • 1970-01-01
  • 1970-01-01
  • 2012-03-11
  • 1970-01-01
  • 2012-07-17
相关资源
最近更新 更多