Catched exception is not handle with the correct method
exception, java
Solution
Overloaded methods are resolved at compile time, based on formal parameter types, not runtime types.
That 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 look for a `thing()` that takes a `B`, because the formal type of `b` is `B`; but
A b = new B();
thing(b);
will look for a `thing()` that takes an `A`, because the formal type of `b` is `A`, even though its runtime actual type will be `B`.
In your code, the formal type of `e` is `AnotherException` in the first case, but `Exception` in the second case. The runtime type is `AnotherException` in each case.
Problem
I have the 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 the method called in the second catch is the one with the signature `void handleException(Exception e)` whereas the kind of exception is `AnotherException`?