Jeremy Robertson
Jeremy Robertson

Reputation: 115

Handling exceptions with interfaces and classes in java

So picture the following scenario. I have two sets of classes and interfaces. ClassA, ClassB, ClassAInterface, and ClassBInterface. ClassA uses ClassB in several of its methods. These methods from ClassB occasionally throw exceptions.

public class ClassA implements ClassAInterface {
   public void example() {
      ClassB test = new ClassB();
      ClassB.exampleTest();

      //more code using ClassB 
   }
}

public class ClassB implements ClassBInterface {
   public void exampleTest() throws ExampleException() {
      boolean tru = false;
      if (tru) {
         throw new ExampleException();
      }
   }
}

So the problem that I'm having is that I'm getting an Unhandled Exception type ExampleException() error in the ClassA.example() method. Why does this happen? I want the ClassB method to throw the exception in specific cases, and signify that it sometimes throws exceptions with throws ExampleException(), so why does ClassA not compile. To solve it, I can't add a throws statement onto ClassA.example() because it would violate ClassAInterface. And if I just wrap ClassB.exampleTest() in a try catch statement, much of the rest of ClassA.example() would throw errors because ClassB signifies something is wrong and you should throw an exception at that point, which is the entire point of throwing an exception`. So I'm not sure why this is happening or how to solve it.

Upvotes: 0

Views: 535

Answers (1)

JB Nizet
JB Nizet

Reputation: 691953

Why does the code refuse to compile?

It's quite normal. As you said, B.exampleTest() sometimes throws an exception. A.example() calls B.exampleTest() and does not catch any exception. So, even if the exception doesn't always happen, it happens sometimes. And when it happens the exception is also thrown by A.example(). So it has to be declared or caught. Just like B.exampleTest() sometimes throws an exception, A.example() also sometimes throws the same exception.

Now, what to do? You have 3 choices:

  1. declare that the exception is thrown: the caller of A.example() will then have to decide what to do in that case.
  2. catch it inside A.example(), and deal with it somehow.
  3. catch it, wrap it inside a runtime exception (which doesn't have to be declared in the throws clause), and throw this runtime exception. The caller will have to deal with this runtime exception, but won't have any hint from the compiler that an exception can be thrown.

Upvotes: 2

Related Questions