Reputation: 31
I am creating a custom exception class using multicatch(Java 7 and above). This is the class that I have created. Please refer to the following code:
public class CustomException extends Exception{
public CustomException() {
System.out.println("Default Constructor");
}
public CustomException(ArithmeticException e, int num){
System.out.println("Divison by ZERO! is attempted!!! Not defined.");
}
public CustomException(ArrayIndexOutOfBoundsException e, int num){
System.out.println("Array Overflow!!!");
}
public CustomException(Exception e, int num){
System.out.println("Error");
}
and the above class is extended by the following class.
import java.util.Scanner;
public class ImplementCustomException extends CustomException {
public static void main(String[] args) throws CustomException {
int num = 0;
System.out.println("Enter a number: ");
try(Scanner in = new Scanner(System.in);){
num = in.nextInt();
int a = 35/num;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException|ArrayIndexOutOfBoundsException e){
throw new CustomException(e, num);
}
}
}
Every time I am trying to run this, it calls the same constructor which is the one with "Exception". Why is that happening?
However, if I replace the multi-catch syntax with the following code. It is working as expected.
catch(ArithmeticException ex){
CustomException e = new CustomException(ex, num);
throw e;
}
catch(ArrayIndexOutOfBoundsException ex){
CustomException e = new CustomException(ex, num);
throw e;
}
Please assist me with the possible changes that I can make in order to use multi catch and make it throw the required exception.
Upvotes: 1
Views: 516
Reputation: 91129
There is no common parent to ArithmeticException
and ArrayIndexOutOfBoundsException
other than Exception
. In this one block
catch(ArithmeticException|ArrayIndexOutOfBoundsException e){
throw new CustomException(e, num);
}
e
gets a static type, and this is Exception
RuntimeException
. With this, the CustomException(Exception e, int num)
is called.
If you split them up, e
has a more dedicated type.
Upvotes: 4
Reputation: 140514
The behaviour is defined in JLS Sec 14.20 via this not-very-prominent sentence:
The declared type of an exception parameter that denotes its type as a union with alternatives
D1 | D2 | ... | Dn
islub(D1, D2, ..., Dn)
.
lub
means "least upper bound", defined in JLS Sec 4.10.4:
The least upper bound, or "lub", of a set of reference types is a shared supertype that is more specific than any other shared supertype (that is, no other shared supertype is a subtype of the least upper bound).
In your case, the lub
of ArithmeticException
and ArrayIndexOutOfBoundsException
is RuntimeException
, so the overload taking Exception
as a parameter type is the most specific method that can be called.
Remember that it is the compiler that decides on the overload to be called: it is not decided at runtime.
Upvotes: 3