Throwable constructors

1.8k views Asked by At

The 4 types of Throwable constructors are :-

Throwable() : Constructs a new throwable with null as its detail message.

Throwable(String message) : Constructs a new throwable with the specified detail message.

Throwable(String message, Throwable cause) : Constructs a new throwable with the specified detail message and cause.

Throwable(Throwable cause) : Constructs a new throwable with the specified cause and a detail message of (cause==null ? null : cause.toString())

In a piece of code, the first two constructors types are working properly, but the other two are reporting compile time error.

IOException e = new IOException();  //Working properly

ArithmeticException ae = new ArithmeticException("Top Layer");  //Working properly

ArithmeticException ae = new ArithmeticException("Top Layer", e);  //Not working

ArithmeticException ae = new ArithmeticException(e);  //Not working

The last two declarations are reporting error

No suitable constructors found for ArithmeticException

I am using JDK 8

Why the last two declarations are reporting error? Also how do I make them work?

2

There are 2 answers

0
Sumit Singh On BEST ANSWER

Because ArithmeticException is a unchecked exceptions and from RuntimeException

RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

From ArithmeticException

there is no constructor as below thats why its giving you compile time error:

AithmeticException ae = new ArithmeticException("Top Layer", e);  //Not working
ae = new ArithmeticException(e);  //Not working

Better use RuntimeException for this:

RuntimeException ae = new RuntimeException("Top Layer", e);  
ae = new RuntimeException(e);
0
JFPicard On

If you check the JavaDoc for ArithmeticException

http://docs.oracle.com/javase/7/docs/api/java/lang/ArithmeticException.html

You will see:

Constructor and Description

ArithmeticException() Constructs an ArithmeticException with no detail message. ArithmeticException(String s) Constructs an ArithmeticException with the specified detail message.

So none of theses constructor are implemented:

Throwable(String message, Throwable cause) : Constructs a new throwable with the specified detail message and cause.

Throwable(Throwable cause) : Constructs a new throwable with the specified cause and a detail message of (cause==null ? null : cause.toString())