Wednesday, 18 September 2013

Warn against all unreported exceptions (including exceptions which super classes of declared exceptions)

Warn against all unreported exceptions (including exceptions which super
classes of declared exceptions)

Consider the following scenario
public class A extends Throwable {}
public class B extends A {}
public class C
{
public void f() throws A, B
{
// Some condition
throw new A();
// Some condition
throw new B();
}
void g()
{
f();
}
}
With the above code, the compiler will warn against not catching (or not
declaring as throws)
C.java:17: unreported exception A; must be caught or declared to be thrown
f();
^
If I fix this with changing g to
void g() throws A
then I get no more warnings (B gets implicitly caught by catching A)
Is there a way to make the compiler report all uncaught exceptions
including the base class ones (like B here).
One way is to change g() and declare it as
public void f() throws B, A
In which case, the compiler will first report B & once I add B to the
throw spec of g, it will report A.
But this is painful because
This is a 2 step process
I may not have control of function f to change it's throw specs.
Is there a better way to make compiler report all exceptions?

No comments:

Post a Comment