Reputation: 115
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
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:
A.example()
will then have to decide what to do in that case.A.example()
, and deal with it somehow.Upvotes: 2