0

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?

gdiazc
  • 2,108
  • 4
  • 19
  • 30

2 Answers2

2

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.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
1

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

kiheru
  • 6,588
  • 25
  • 31
  • `RuntimeException` is a subclass of `Exception`, so that explains which `Exception`s don't require the `throws`, but `Error` is not a subclass of `RuntimeException`, so how do we include `Error`s in that criterium? – gdiazc Jul 18 '13 at 14:21
  • Errors are not a subclass of Exception. They do not need declaring either (count as unchecked, like run time exceptions), but you should not be throwing or catching them anyway, unless you really know what you're doing. Any Throwable that's not a RuntimeException or Error is checked. – kiheru Jul 18 '13 at 14:29