Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java casting an exception (not class cast exception)

Tags:

java

casting

When an exception is caught in java is there a use case for casting the exception to a new type? Or is the standard

    throw new DiffException(e)

The only way to do it. I apologize if I'm overlooking something but the only search results I get are for "ClassCastExceptions" Which is obviously not what I'm looking for

like image 599
Matt Phillips Avatar asked Oct 29 '25 14:10

Matt Phillips


1 Answers

I believe you meant 'exception wrapping'. There's no other way to do it - you create a new instance of Exception using a constructor which takes another exception as cause. This works thanks to 1-arg constructor of java.lang.Exception. The typical implementation of custom exception type (like your DiffException) declares such 1-arg constructor too.

like image 192
Grzegorz Oledzki Avatar answered Oct 31 '25 05:10

Grzegorz Oledzki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!