In Java, there are some kinds of exceptions which require a throws statement:

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

while others don't:

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

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

The first method wont compile wthout the throws statement.

What is the criteria for determining if an Exception/Error requires a throws statement?

有帮助吗?

解决方案

Exception checked and complained by the compiler are called Checked Exceptions in 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.

Read more from JLS: http://docs.oracle.com/javase/specs/jls/se5.0/html/exceptions.html

IOException is a checked exception and hence java compiler asks you to either catch it or throw it. While IllegalArgumentException is a run time exception and is not checked or complained by the compiler.

其他提示

Exceptions derived from RuntimeException do not need to be declared, others do.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top