Reputation: 5375
How come I can have
public void someMethod() {
throw new UnsupportedOperationException();
}
but not
public void someMethod() {
throw new throw new IOException();
}
The first is fine, the second generates the compile error "unhandled exception type IOException".
Upvotes: 1
Views: 132
Reputation: 424983
All things that can be thrown are Throwable
. There are two types of Throwable
:
One subclass of Exception
is RuntimeException
, which is "unchecked" - meaning you don't have to declare or catch them. These are generally for "programming errors", like NullPointerException
or ArrayOutOfBoundsException
.
Errors
are also "unchecked" and are for "unrecoverable" situations, such as OutOfMemoryError
etc.
Any Throwable not a subclass of Error
or RuntimeException
is "checked" and must be declared as thrown or caught.
Upvotes: 5
Reputation: 20061
UnsupportedOperationException
is a RuntimeException which is a type of unchecked exception. These are exceptions that arise during the execution of a program and indicate a state that is unlikely to be recovered from.
Checked exceptions, the type you must handle in some way, are exceptions that you can probably write code to handle gracefully.
The Java Language Specification, section 11.2.5, states it very well:
The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking because, in the judgment of the designers of the Java programming language, having to declare such exceptions would not aid significantly in establishing the correctness of programs.
There are some good explanations of the idea behind the two types. The Java Tutorial has a page titled Unchecked Exceptions — The Controversy, and if you want a more lengthy discussion see Checked or Unchecked Exceptions?
Upvotes: 1
Reputation: 7335
Yo need to look at the difference between check and unchecked exceptions.
Upvotes: 1
Reputation: 6173
IOException is a checked exception while UnsupportedOperationException is a RuntimeException (unchecked). Checked exceptions must be caught or rethrown. http://java.sun.com/docs/books/jls/second_edition/html/exceptions.doc.html
Upvotes: 1
Reputation: 160170
Because RuntimeException
s and its subclasses are "unchecked" exceptions and do not need to be declared thrown, or caught. Checked exceptions do.
JLS 11, Exceptions covers exceptions in exhaustive detail, JLS 11.2, Compile-Time Checking of Exceptions discusses the differences at a high level.
Upvotes: 1
Reputation: 76888
There are two types of exceptions in java; checked
and unchecked
.
You have to catch or specify that your method throws checked
exceptions. That's the case in your second example with IOException
.
http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
Upvotes: 1