Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can a method be declared to throw many exceptions even if none of them are thrown?

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
}
like image 648
Pedro García Medina Avatar asked Mar 17 '15 22:03

Pedro García Medina


People also ask

Why do methods have to declare the exceptions they can throw?

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.

Can a method declare to throw multiple exceptions?

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();

When multiple exceptions are to be thrown which clause is used?

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 .

Does each exception which can be thrown by a method need to be declared with throws?

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.


1 Answers

  1. Subclasses that override the method may throw the exception, even if its superclass doesn't.
  2. You can later change the method to throw one of the listed exceptions while maintaining backwards compatibility.
like image 193
Colonel Thirty Two Avatar answered Sep 22 '22 04:09

Colonel Thirty Two