I was merging my source code with that of a colleague and I saw he had added an exception to be thrown in the declaration of a method; however, I knew, that exception would never be really thrown from that method.
I wonder why the compiler did not warn me about a "non-thrown exception declared" (or something like that). I realize that you can declare a method throwing N exceptions, even if none of those exceptions is thrown by the code in the method.
Why is that?
public void foo() throws IOException, IntrospectionException, BadStringOperationException, ... {
//do nothing
}
When a method declares that it throws an exception, it is not required to handle the exception. The caller of a method that throws exceptions is required to handle the exceptions (or throw them to its caller and so on) so that the flow of the program can be maintained.
You can have the possibility of throwing multiple different exceptions. For example: if (obj == null) throw new NullPointerException(); if (some other case) throw new IllegalArgumentException(); if (this == this) throw new IOException();
The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar ( | ). Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final .
Exception is a checked exception class. Therefore, any code that calls a method that declares that it throws Exception must handle or declare it. Every method in the chain is declared to throw Exception, including main.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With