Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should the methods of the interfaces throw exceptions?

I mean, in the definition. If I have a method of a class that implements an interface and I want to throw an exception, how can I do that if the interface don't have a throws declaration.

Thanks

like image 359
Gabriel Llamas Avatar asked Dec 06 '22 00:12

Gabriel Llamas


2 Answers

How is the code relying on your class implementing the interface going to know that it has to handle the new exception? You have two options:

  1. Handle it in the interface method.
  2. Throw an exception that inherits from RuntimeException, which doesn't need to be in the throws clause. However, any code calling this method does not have to catch this exception nor does it know that it can be thrown. So be careful when using this option. Document them where possible, but you'll still face a problem when passing an object to an existing method such as a library or one that is built-in.
like image 63
moinudin Avatar answered Dec 08 '22 04:12

moinudin


You simply don't or throw a RuntimeException.

like image 26
mtraut Avatar answered Dec 08 '22 05:12

mtraut