Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Exception and Throwable classes?

I am new to the exception handling in Scala. Java states that Exception is the superclass of all exceptions. Similarly Throwable is the superclass of all exceptions in Scala. But recently I have come across "Exception" class being used in a lot of Scala codes too. Can you please tell me the difference between Throwable class and Exception class in Scala.

like image 770
Siraj Avatar asked Oct 20 '25 03:10

Siraj


1 Answers

Actually, Scala reuses exception structure from Java (so Throwable comes from Java). The class hierarchy looks like this:

         Throwable
            |
    ------------------
    |                |
  Error          Exception
    |                |
  errors             |
             -------------------
             |                 |
     runtime exceptions   checked exceptions

Throwable is the superclass of all errors in Java.

Error is the superclass for errors, that are not recoverable like VirtualMachineError or ThreadDeath. Errors can be intercepted using try-catch, but usually, it's not a good practice.

Child classes of Exception are exceptions, that are intended to handled programmatically by intercepting them using try-catch.

Java also makes the difference between runtime and checked exceptions, that checked exception need to be mandatorily handled by try-catch.

Scala though handles all exceptions as runtime, so intercepting them is voluntary.

Scala has also extractor named NonFatal, which can be used to pattern match non-fatal Throwables. For example:

try {
  // dangerous stuff
} catch {
  //will NOT match fatal errors like VirtualMachineError, ThreadDeath, LinkageError etc.
  case NonFatal(e) => log.error(e, "Something not that bad.") 
}
like image 130
Krzysztof Atłasik Avatar answered Oct 21 '25 19:10

Krzysztof Atłasik



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!