Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are reasons for Exceptions not to be compatible with throws clauses?

Tags:

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

like image 536
Franz Ebner Avatar asked May 09 '12 09:05

Franz Ebner


People also ask

Which type of exception must be caught with a throws clause?

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.

Can we handle exception with throws?

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.

How many exceptions we can define in throws clause?

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.

Which exceptions do you need to declare with the throws keyword?

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.


1 Answers

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).

like image 181
Péter Török Avatar answered Oct 13 '22 20:10

Péter Török