The thrown exception is not a handle with the correct method
I have a simple code below:
class Test {
public static void main(String[] args) {
Test t = new Test();
try {
t.throwAnotherException();
} catch (AnotherException e) {
t.handleException(e);
}
try {
t.throwAnotherException();
} catch (Exception e) {
System.out.println(e.getClass().getName());
t.handleException(e);
}
}
public void throwAnotherException() throws AnotherException {
throw new AnotherException();
}
public void handleException(Exception e) {
System.out.println("Handle Exception");
}
public void handleException(AnotherException e) {
System.out.println("Handle Another Exception");
}
}
class AnotherException extends Exception {
}
Why is the method called in the second catch the one that has the signature void handleException(Exception e)
, then as a kind of exception AnotherException
?
source to share
Overloaded methods are resolved at compile time based on formal parameter types, not run-time types.
This means that if B extends A
, and you have
void thing(A x);
void thing(B x);
then
B b = new B();
thing(b);
will search thing()
which accepts B
because the formal type B
is B
; but
A b = new B();
thing(b);
will look for thing()
which takes A
as the formal type B
is equal A
, although its actual execution type will be B
.
In your code, the formal type e
is equal AnotherException
in the first case, but Exception
in the second case. Execution type - AnotherException
in each case.
source to share
I think you wanted to check which one Exception
gets caught, right?
Then change your code to throw just one Exception
:
try {
t.throwAnotherException();
} catch (AnotherException e) {
t.handleException(e);
}
catch (Exception e) {
System.out.println(e.getClass().getName());
t.handleException(e);
}
which works as expected.
source to share
Exception
is a superclass, so if you write your catch clause with (Exception e) it will always satisfy and execute.
to improve your code, you can change your code as below.
class Test {
public static void main(String[] args) {
Test t = new Test();
try {
t.throwAnotherException();
} catch (AnotherException e) {
t.handleException(e);
}
try {
t.throwAnotherException();
}catch (AnotherException e) {
t.handleException(e);
}catch (Exception e) {
System.out.println(e.getClass().getName());
t.handleException(e);
}
}
public void throwAnotherException() throws AnotherException {
throw new AnotherException();
}
public void handleException(Exception e) {
System.out.println("Handle Exception");
}
public void handleException(AnotherException e) {
System.out.println("Handle Another Exception");
}
}
class AnotherException extends Exception {
}
source to share