0

Why when I throw a RuntimeException inside of a method I don't get any error but when I throw an IOException inside of a method I need to throw the exception from the method as well?

public void throwException() {
    throw new RuntimeException();
}

This works fine. The same thing happens when I throw IndexOutOfBoundsException, NullPointerException and InputMismatchException and so on.

But when I throw IOException, the method has to throw an IOException too:

public void throwException() throws IOException {
    throw new IOException();
}
Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
parsa
  • 987
  • 2
  • 10
  • 23

3 Answers3

2

The RuntimeException is an unchecked exception, and you do not need to mark your method as throwing this exception. From the docs:

Because the Java programming language does not require methods to catch or to specify unchecked exceptions (RuntimeException, Error, and their subclasses), programmers may be tempted to write code that throws only unchecked exceptions or to make all their exception subclasses inherit from RuntimeException.

As the name implies, you are not expected to check for such a runtime exception, hence the language spec does not require you to mark the method with throws.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

IOException is a (so to say) regular exception, and it's not a subclass of RuntimeException, which is a superclass of a special kind of exception.

Taken from the API (emphasys mine)

RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.

RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

SCouto
  • 7,808
  • 5
  • 32
  • 49
0

You are basicly asking this question. IOException is a more specific Java.Lang.Exception

Difference between java.lang.RuntimeException and java.lang.Exception

Marcus Lanvers
  • 383
  • 5
  • 20