Java: 自动 'throws' 声明:是吗,如果是,它的值是多少?
Java: Automatic 'throws' declaration: is it, and if so, what is its value?
以任何方法为例。 public static void main(String[] args)
和其他的一样好。例如,如果我的代码会抛出一个 NullPointerException
,为什么我不必声明我的方法会抛出这个?
假设没有定义,所有方法都会抛出一些特定的预定义异常,对吗?如果有,它们是什么?
澄清一下,我不是在寻求有关损坏代码的帮助,而是在询问有关 Java 本身如何工作的问题。
主要有两组Exception
。一种是继承RuntimeException
的人。您无需定义它(如 void f() throws SomeException
)。这些被称为未经检查的异常。
对于其他的你必须这样做。它们被称为 checked exception.
有关详细信息,请参阅 here
Java 有已检查和未检查的异常。来自 documentation:
The unchecked exception classes are the run-time exception classes and the error classes.
The checked exception classes are all exception classes other than the unchecked exception classes. That is, the checked exception classes are all subclasses of Throwable other than RuntimeException and its subclasses and Error and its subclasses.
NullPointerException
是未经检查的异常的示例。这意味着您不会被迫捕获它或为每个有机会抛出它的方法添加 throws NullPointerException
。
FileNotFoundException
是检查异常。因此,如果您使用抛出 FileNotFoundException
的 FileInputStream
,您需要用 try-catch 块包围它,或者声明它所在的方法抛出 FileNotFoundException
.
运行时异常表示由编程问题引起的问题,因此,API 客户端代码不能合理地期望从它们中恢复或以任何方式处理它们。此类问题包括算术异常,例如除以零;指针异常,例如试图通过空引用访问对象;和索引异常,例如试图通过太大或太小的索引访问数组元素。
运行时异常可能发生在程序的任何地方,在一个典型的程序中它们可能非常多。必须在每个方法声明中添加运行时异常会降低程序的清晰度。因此,编译器不要求您捕获或指定运行时异常(尽管您可以)。
http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
以任何方法为例。 public static void main(String[] args)
和其他的一样好。例如,如果我的代码会抛出一个 NullPointerException
,为什么我不必声明我的方法会抛出这个?
假设没有定义,所有方法都会抛出一些特定的预定义异常,对吗?如果有,它们是什么?
澄清一下,我不是在寻求有关损坏代码的帮助,而是在询问有关 Java 本身如何工作的问题。
主要有两组Exception
。一种是继承RuntimeException
的人。您无需定义它(如 void f() throws SomeException
)。这些被称为未经检查的异常。
对于其他的你必须这样做。它们被称为 checked exception.
有关详细信息,请参阅 here
Java 有已检查和未检查的异常。来自 documentation:
The unchecked exception classes are the run-time exception classes and the error classes.
The checked exception classes are all exception classes other than the unchecked exception classes. That is, the checked exception classes are all subclasses of Throwable other than RuntimeException and its subclasses and Error and its subclasses.
NullPointerException
是未经检查的异常的示例。这意味着您不会被迫捕获它或为每个有机会抛出它的方法添加 throws NullPointerException
。
FileNotFoundException
是检查异常。因此,如果您使用抛出 FileNotFoundException
的 FileInputStream
,您需要用 try-catch 块包围它,或者声明它所在的方法抛出 FileNotFoundException
.
运行时异常表示由编程问题引起的问题,因此,API 客户端代码不能合理地期望从它们中恢复或以任何方式处理它们。此类问题包括算术异常,例如除以零;指针异常,例如试图通过空引用访问对象;和索引异常,例如试图通过太大或太小的索引访问数组元素。
运行时异常可能发生在程序的任何地方,在一个典型的程序中它们可能非常多。必须在每个方法声明中添加运行时异常会降低程序的清晰度。因此,编译器不要求您捕获或指定运行时异常(尽管您可以)。
http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html