Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Throwable to Exception

I am currently using the play2 framework.

I have several classes which are throwing exceptions but play2s global onError handler uses throwable instead of an exception.

for example one of my classes is throwing a NoSessionException. Can I check a throwable object if it is a NoSessionException ?

like image 369
Maik Klein Avatar asked Sep 10 '12 20:09

Maik Klein


People also ask

Can I cast throwable to exception?

We can pass Throwable to Exception constructor.

How do you make an exception throwable?

Using the Throws keyword Throws is a keyword used to indicate that this method could throw this type of exception. The caller has to handle the exception using a try-catch block or propagate the exception. We can throw either checked or unchecked exceptions.

Can we handle throwable in Java?

Don't Catch Throwable Throwable is the superclass of all exceptions and errors. You can use it in a catch clause, but you should never do it! If you use Throwable in a catch clause, it will not only catch all exceptions; it will also catch all errors.

Is throwable subclass of exception?

The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement.


3 Answers

Just make it short. We can pass Throwable to Exception constructor.

 @Override
 public void onError(Throwable e) {
    Exception ex = new Exception(e);
 }               

See this Exception from Android

like image 64
THANN Phearum Avatar answered Oct 21 '22 07:10

THANN Phearum


You can use instanceof to check it is of NoSessionException or not.

Example:

if (exp instanceof NoSessionException) {
...
}

Assuming exp is the Throwable reference.

like image 35
kosa Avatar answered Oct 21 '22 05:10

kosa


Can I check a throwable object if it is a NoSessionException ?

Sure:

Throwable t = ...;
if (t instanceof NoSessionException) {
    ...
    // If you need to use information in the exception
    // you can cast it in here
}
like image 15
Jon Skeet Avatar answered Oct 21 '22 07:10

Jon Skeet