Can anyone tell me what reasons exceptions can have, not to be compatible with "throws" clauses
For instance:
class Sub extends Super{ @Override void foo() throws Exception{ } } class Super{ void foo() throws IOException{ } }
Exception Exception is not compatible with throws clause in Super.foo()
The throws clause must be used with checked exceptions. The throws clause is followed by the exception class names. The throws clause is used in a method declaration. Using the throws clause, we can declare multiple exceptions at a time.
The throws keyword can be useful for propagating exceptions in the call stack and allows exceptions to not necessarily be handled within the method that declares these exceptions. On the other hand, the throw keyword is used within a method body, or any block of code, and is used to explicitly throw a single exception.
In Java, exceptions can be categorized into two types: Unchecked Exceptions: They are not checked at compile-time but at run-time. For example: ArithmeticException , NullPointerException , ArrayIndexOutOfBoundsException , exceptions under Error class, etc. Checked Exceptions: They are checked at compile-time.
The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.
Without a full code sample, I can only guess: you are overriding/implementing a method in a subclass, but the exception specification of the subclass method is not compatible with (i.e. not a subset of) that of the superclass/interface method?
This can happen if the base method is declared to throw no exceptions at all, or e.g. java.io.IOException
(which is a subclass of java.lang.Exception
your method is trying to throw here). Clients of the base class/interface expect its instances to adhere to the contract declared by the base method, so throwing Exception
from an implementation of that method would break the contract (and LSP).
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