I have the following program -
private static void fun() throws Error {
System.out.println("I am having fun");
throw new Error();
}
private static void enjoy() {
System.out.println("I am enjoying");
throw new Error();
}
public static void main(String[] args) {
try {
fun();
} catch(Error e) {
System.out.println(e);
}
System.out.println("\n");
try {
enjoy();
} catch(Error e) {
System.out.println(e);
}
}
Here, I have declared two methods - fun()
and enjoy()
Both has
throw new Error()
statement
However,
fun()
has throws Error
appended to method declaration
while,
enjoy()
doesn't have it.
But both is giving the similar output -
I am having fun
java.lang.Error
I am enjoying
java.lang.Error
So, here what is the significance of appending throws Error
to method declaration?
There are two kinds of exceptions in Java. Checked and Unchecked. You do not need to add throws
for unchecked exceptions. You also do not need to catch
them. This is not a coincidence. That is the difference between checked and unchecked exceptions. Error
(to be explicit) is an unchecked exception and the Javadoc says (in part)
That is, Error and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions.