java - 哪些异常需要方法的 throws 语句?

标签 java exception error-handling throws

在 Java 中,有一些异常需要 throws 语句:

public void myMethod() throws IOException {
  throw new IOException("Error!");
}

而其他人则不然:

public void myOtherMethod() {
  throw new IllegalArgumentException("Error!");
}

public void myThirdMethod() {
  throw new Error("Error!");
}

如果没有throws,第一种方法将无法编译声明。

判断是否Exception的标准是什么?/Error需要 throws声明?

最佳答案

编译器检查和提示的异常在java中称为检查异常

At compile time, the java compiler checks that a program contains handlers for checked exceptions. Java compiler analyzes by which checked exceptions can result from execution of a method or constructor.For each checked exception which is a possible result, the throws clause for the method or constructor must mention the class or its superclasses of that exception.

从 JLS 了解更多信息:http://docs.oracle.com/javase/specs/jls/se5.0/html/exceptions.html

IOException 是一个检查异常,因此 java 编译器要求您捕获它或抛出它。而 IllegalArgumentException 是一个运行时异常,编译器不会检查或提示。

关于java - 哪些异常需要方法的 throws 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17726033/

相关文章:

c# - 返回 bool 值并重新抛出异常

react-native - 无法捕获由redux-saga call()引发另一个错误的错误

python - 未定义全局变量 - Python

java - 在 JpaRepository 的查询中执行 PostGIS 函数

java - 使用 libgdx 时字符串固定在屏幕上

java - 为什么我得到 NoClassDefFoundError : java/awt/Desktop?

asp.net-mvc-4 - 我想在mvc4中文本框为null时显示错误消息

java - 从线程返回值

java - 用 swagger 隐藏 api 模型属性

c++ - 为什么 "non-standard syntax; use ' &' to create a pointer to member"在 CTOR 中使用线程?