Gabriel Llamas
Gabriel Llamas

Reputation: 18437

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

Upvotes: 4

Views: 7874

Answers (4)

Costi Ciudatu
Costi Ciudatu

Reputation: 38235

The methods in your interface can declare to throw checked exceptions only if it makes sense for all the possible implementations to force the client to handle that exception. Think of java.sql.Connection (an interface with all the methods throwing SQLException). Otherwise, if only one particular implementation has to deal with some checked exception, handle it there and either wrap it in some RuntimeException and rethrow or recover from that state if it makes sense.

Upvotes: 3

moinudin
moinudin

Reputation: 138417

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.

Upvotes: 5

barjak
barjak

Reputation: 11270

If you cannot touch the interface, then your only choice is to throw a RuntimeException. There are some standard RuntimeExceptions that you can use directly : IllegalStateException, IllegalArgumentException, UsupportedOperationException, etc.

Use these standard exceptions if they suit your needs, or create your own by extending the class RuntimeException. Consider documenting the thrown exceptions by using the @throws doclet in the javadoc.

Upvotes: 3

mtraut
mtraut

Reputation: 4740

You simply don't or throw a RuntimeException.

Upvotes: 5

Related Questions