Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the compiler allow throws when the method will never throw the Exception

I am wondering why the java compiler allows throws in the method declaration when the method will never throw the Exception. Because "throws" is a way of handling the exception (telling the caller to handle it).

Since there are two ways of handling exception (throws & try/catch). In a try/catch, it doesn't allow the catch of an exception not thrown in the try block but it allows a throws in a method that does may not throw the exception.

private static void methodA() {
    try {
        // Do something
        // No IO operation here
    } catch (IOException ex) {  //This line does not compile because
                              //exception is never thrown from try
        // Handle   
    }
}

private static void methodB() throws IOException { //Why does this //compile when excetion is never thrown in function body
    //Do Something 
    //No IO operation
}
like image 961
PsyAp Avatar asked Mar 25 '19 09:03

PsyAp


People also ask

What happens when a method throws an exception?

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.

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

If the programmer did not declare that the method (might) throw an exception (or if Java did not have the ability to declare it), the compiler could not know and it would be up to the future user of the method to know about, catch and handle any exceptions the method might throw.

Can we throw an exception without throws?

Without using throws When an exception is cached in a catch block, you can re-throw it using the throw keyword (which is used to throw the exception objects). If you re-throw the exception, just like in the case of throws clause this exception now, will be generated at in the method that calls the current one.

What happens if an exception is thrown and not caught?

What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console. The message typically includes: name of exception type.

How to throw an exception without using throws in Java?

1 Example 2 Output 3 Without using throws. When an exception is cached in a catch block, you can re-throw it using the throw keyword (which is used to throw the exception objects). 4 Example. In the following Java example our code in demo method () might throw ArrayIndexOutOfBoundsException an ArithmeticException.

When should a method throw a checked exception?

When a contract violation can, must, or should be handled by the consumer’s code, the method should throw a checked exception. Methods should never return null to represent contract failure.

What is the purpose of the throws clause in Java?

Generally, throws clause added to any method indicates that; corresponding method is possibly throws some exception and it need to be handled invoker or caller. In a similar way, caller of main() method i.e.; JVM need to handle the exception thrown from main() method.

What does it mean to throw an exception in C++?

Generally throws Exception is frowned upon in production code as Exception includes all exceptions; you’d expect a It tells the compiler (and any code that directly calls main) that any exception may be thrown, including so called “checked exceptions” that don’t derive from the unchecked RuntimeException.


2 Answers

The throws clause is part of the method's contract. It requires the caller of the method to behave as if the specified exception may be thrown by the method (i.e. either catch the exception or declare their own throws clause).

It's possible that the initial version of a method does not throw the exception specified in the throws clause, but a future version can throw it without breaking the API (i.e. any existing code that calls the method will still pass compilation).

The opposite it also possible. If the method used to throw the exception specified in the throws clause, but a future version of it doesn't throw it anymore, you should keep the throws clause in order not to break existing code that uses your method.

First example:

Suppose you have this code which uses methodB:

private static void methodA() {
    methodB(); // doesn't have throws IOException clause yet
}

If later you want to change methodB to throw IOException, methodA will stop passing compilation.

Second example:

Suppose you have this code which uses methodB:

private static void methodA() {
    try {
        methodB(); // throws IOException
    }
    catch (IOException ex) {

    }
}

If you remove the throws clause from a future version of methodB, methodA won't pass compilation anymore.

This example is not very interesting when methodA is private, because it can only be used locally (within the same class, where it's easy to modify all the methods that call it).

However, if it becomes public, you don't know who uses (or will use) your method, so you have no control of all the code that may break as a result of adding or removing the throws clause.

And if it's an instance method, there's another reason for allowing the throws clause even if you don't throw the exception - the method can be overridden, and the overriding method may throw the exception even if the base class implementation does not.

like image 147
Eran Avatar answered Sep 27 '22 15:09

Eran


Because the signature defines the contract of the method. Even if the method doesn't throw an IOException now, maybe it will in the future, and you want to prepare for that possibility.

Suppose you just provide a dummy implementation for the method for now, but you know that, later, the actual implementation will potentially throw an IOException. If the compiler prevented you from adding this throws clause, you would be forced to rework all the calls (recursively) to that method once you provide the actual implementation of the method.

like image 35
JB Nizet Avatar answered Sep 27 '22 15:09

JB Nizet