Should interface methods throw exceptions?

I mean, in the definition. If I have a class method that implements the interface, and I want to throw an exception, how can I do this if the interface does not have a throws declaration.

thanks

+4
source share
4 answers

How will code that relies on your class that implements the interface know that it should handle the new exception? You have two options:

  • Handle it in an interface method.
  • Throw an exception that inherits from RuntimeException , which does not have to be in the throws . However, any code that calls this method should not catch this exception and does not know that it can be thrown. Therefore, be careful when using this option. Write them down where possible, but you still encounter a problem when passing an object to an existing method, such as a library or built-in.
+5
source

You simply do not or do not throw a RuntimeException.

+5
source

If you cannot touch the interface, then your only choice is to throw a RuntimeException . There are several 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 RuntimeException class. Consider documenting thrown exceptions using @throws in javadoc.

+3
source

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

+3
source

Source: https://habr.com/ru/post/1333888/


All Articles