Reputation: 18437
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
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
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:
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
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