Java interface exception method

Should the methods of the interfaces throw exceptions?

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.

How is the code relying on your class implementing the interface going to know that it has to handle the new RuntimeException ?

@marcog: So your point with «How is the code relying on your class implementing the interface going to know that it has to handle the new exception?» was?

@marcog: Sorry if I came across a bit rude. This is a big nuissance in Java, and I’m tired of seeing people cheating the system and thinking everything will be alright. Glad you edited a warning into your answer.

You simply don’t or throw a RuntimeException.

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.

And the corollary, of course: If you are in control of the interface, ensure that it declares appropriate checked exceptions (if any) and also use the @throws doclet to document any runtime exceptions implementations may be expected to throw. (No need to go overboard on that latter, but for instance an interface that accepts an index value should state clearly how implementations are expected to respond to an invalid index — by returning some kind of flag value [like null ], or by throwing an exception like IllegalArgumentException ). The more thorough the interface docs, the better.

Источник

Throw exception in interface default method

Later, it turned out that it’s general convention for this project. Is it considered a good practice?

So, while the usage you outline is often acceptable (it’s the «optional method» idiom), the fact that this is a «general convention» in your project is a huge screaming red flag. To put this in perspective, I’ve used this pattern only a handful of times (for example, Iterator.remove() .) To see it used regularly as a «general convention» is almost certainly overuse.

Читайте также:  Java получить цвет пикселя

More generally, regular use of such a convention is effectively downgrading «implements interface» from a statically typed property to a dynamically typed one. Which will invariably blow up in the hands of unsuspecting and undeserving users, since they have reason to believe that «implements Foo» really means «implements Foo.» True optionality is rare; treat it as such.

2 Answers 2

One could starte here to see what Brian Goetz, one of the «acting fathers» of Java has to say about «how to use default methods».

So, according «to the books»; one could use them like in your example: to throw an exception for a method regarded «optional». But that would mean: you have already some methods; and you are adding new ones.

The main purpose of adding default methods to the Java language was to allow for non-breaking enhancements of existing interfaces. They were not meant to be used as some sort of «mixin» / multi-inheritance / traits-like providing construct.

But beyond that: in your example, you have a new interface . that only has that one method. I think this does not fall under those «intended usages».

On the other hand; don’t be too much «about the books». When a whole team of people agrees «this is what we do», and everybody understands and buys into that; why not?!

But there is one caveat . my C++ coworkers have a strict policy: they allow for exactly one implementation of any abstract method within an inheritance tree; as it is very hard to debug a problem when you are looking at the wrong implementation of some method. And now that we can inherit default methods in Java, too . debugging problems could become harder in Java for us in the same way. So be careful how such things are used!

Long story short: it is a good practice if the big majority of your development team finds it a helpful practice. If not, it is not.

Источник

Exception handling and interfaces in Java

I have written an interface and an implementation to it and I can’t really decide on the best way to handle the following problem. To make it short, let’s say this is the interface:

Now if I wanted to handle exceptions, is it a good idea to make the exception as generic as possible or should I add rather specific ones? Let’s say the method addChild, should it throw a generic NodeException that could potentially be used in any other method so that the implementing class can extend it on demand, or is it okay to go with a NodeAdditionException that only this methods should throw? The advantage of a generic exception would be that I don’t need to wrap exceptions if I use one of the methods internally and an exception is throws, I can just let it go up the stack until someone catches it. It will usually go up to the caller of my implementation and he needs to deal with it then. The caller can catch the generic exception to handle all the exceptions with just one routine or catch any of the child classes. This is at the same time a huge disadvantage, as the caller potentially could catch many different child exceptions that don’t even need to be used in the current implementation. That is kind of a deal breaker. A way to solve this is to create a set of fixed exceptions for the implementation to be used which also isn’t what I would want to do. The other way would be the specific exception but this also comes at a price. You would have a fixed set of exception that can be thrown and that’s it, an advantage, but if you use any method internally you need to catch the exception, wrap it up in a new one and throw it again. If I got it right, this is quite resource heavy and it’s a lot of boiler plate code to write, too. In the end I would take this as the cleaner method to handle exception. Is there any other way to handle exceptions but this that I just can’t think off right now, have I overlooked an important detail on these two or do I need to chose the lesser of these two evils? Any help appreciated.

Читайте также:  Проверка введенных данных java

Источник

Should the methods of the interfaces throw exceptions?

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.

How is the code relying on your class implementing the interface going to know that it has to handle the new RuntimeException ?

@marcog: So your point with «How is the code relying on your class implementing the interface going to know that it has to handle the new exception?» was?

@marcog: Sorry if I came across a bit rude. This is a big nuissance in Java, and I’m tired of seeing people cheating the system and thinking everything will be alright. Glad you edited a warning into your answer.

You simply don’t or throw a RuntimeException.

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.

Читайте также:  Конструкция метода в java

And the corollary, of course: If you are in control of the interface, ensure that it declares appropriate checked exceptions (if any) and also use the @throws doclet to document any runtime exceptions implementations may be expected to throw. (No need to go overboard on that latter, but for instance an interface that accepts an index value should state clearly how implementations are expected to respond to an invalid index — by returning some kind of flag value [like null ], or by throwing an exception like IllegalArgumentException ). The more thorough the interface docs, the better.

Источник

Throwing multiple exceptions in a method of an interface in java

i want to say that i can mention One exception in an interface but how to mention in my interface that my method will throw Two exceptions Namely A and B. the code fragment mentioned above works only for A and not for B. Help

public interface dictionary < public void insert(int x) throws Dictionary_FullException, Duplicate_Element_FoundException; >. public class SortedArray implements dictionary

SortedArray.java:66: insert(int) in assign.SortedArray cannot implement insert(int) in assign.dictionary; overridden method does not throw assign.SortedArray.Duplicate_Element_FoundException public void insert(int x) throws Dictionary_FullException

3 Answers 3

You can declare as many Exceptions as you want for your interface method. But the class you gave in your question is invalid. It should read

public class MyClass implements MyInterface < public void find(int x) throws A_Exception, B_Exception< ---- ---- --- >> 

Then an interface would look like this

public interface MyInterface

I think you are asking for something like the code below:

public interface A < void foo() throws AException; >public class B implements A < @Overrides public void foo() throws AException, BException < >> 

This will not work unless BException is a subclass of AException. When you override a method you must conform to the signature that the parent provides, and exceptions are part of the signature.

The solution is to declare the the interface also throws a BException.

The reason for this is you do not want code like:

public class Main < public static void main(final String[] argv) < A a; a = new B(); try < a.foo(); >catch(final AException ex) < >// compiler will not let you write a catch BException if the A interface // doesn't say that it is thrown. > > 

What would happen if B::foo threw a BException? The program would have to exit as there could be no catch for it. To avoid situations like this child classes cannot alter the types of exceptions thrown (except that they can remove exceptions from the list).

Источник

Оцените статью