0

I'm thinking of implementing better ways of error handling through exceptions. When I'm deep in my code and want to return an error, I have two options:

  1. Throw an exception that extends runtime exception.
  2. Pass error message objects along with my response. This allows each level to handle an error if needed by looking at the error message.

I like 1. However, let's say I create an interface:

public interface Interface {
  method1();
  method2();
}

Now, in this type of contract, I haven't seen interfaces that declare the methods as:

method1() throws ExtendedRuntimeException;
method2() throws ExtendedRuntimeException;

What is a cleaner way of specifying that the implemetation needs to handle the extended runtime exception?

JJD
  • 50,076
  • 60
  • 203
  • 339
Sudoer
  • 451
  • 2
  • 5
  • 13
  • in general, a method declaring 'throws ' is saying 'I won't handle the exception'. So methods that don't explicitly specify this on their contract should be thought as handlers of such. – Dan Apr 19 '12 at 22:44

3 Answers3

0

You need a combined approach. When designing the exception handling mechanism in your application you will need to design interface that force the impl to handle exceptions. These are checked exceptions.

Also you will have to before hand decide a layer that handles all the exceptions or decides what to do with the exceptions. All lower layers pass the exception up i.e. bubble the exception up. You can do it by creating your exception subclasses or simply throw the exceptions as it is. Best is to create an exception subclass with more details like error code/message etc.

And yes many designs have interfaces that do have the throws attached to method definitions.

HTH ~Ayusman

Ayusman
  • 8,509
  • 21
  • 79
  • 132
0

Sudoer, IMHO you cannot control that implementers of your interface handle runtime (a.k.a unchecked) exceptions.

Like @Ayusman mentioned you could declare and require the implementers to handle checked exception but for runtime exception its always obliged they are not required to declare it. Also, for unchecked exceptions as an implementer I can throw my own runtime exception that as an interface designer you haven't declared.

That's true because you declare only a contract, but you would not have enough context into what kind of runtime exceptions are possible. Hope I could convey the idea here.

I found these useful:

Hope that helps.

g13n
  • 3,218
  • 2
  • 24
  • 19
0

There are many schools of thought on exception error handling. A long but very informative article can be found here: http://articles.vconst.com/2009/08/error-handling-and-exceptions-in-java.html

He actually suggests putting a throws declaration for runtime exceptions.

dnc253
  • 39,967
  • 41
  • 141
  • 157