Scala Exception Handling by Code Examples

Scala Exception handling is mostly very similar with Java exception handling except catch block syntax. Here I am just trying you to explain Scala exception handling concept in brief as it is a very vast topic in itself.

Before we go into the much details, first let me highlight understand the primary points regarding exception handling in Scala,

What are Exceptions in Scala?

Exception is an explicit constructs to handle expected or unexpected failures within your Scala code. Such failures could be due to,

  • Operation failure due to mismatch in any condition (i.e. Wrong values of the parameters)
  • Operation failure due to some resource is not available or error in accessing the same (i.e. Database connection failure)
  • Operation failure due to some abnormal condition occurs in your code (i.e. any operation is doing divide by zero)

How to throw an Exception in Scala?

Throwing an exception is as simple as in Java. You create an Exception object and throw it by keyword throw.

Scala try, catch and finally blocks

In above code block,

  • If score is positive than method printScore() returns value otherwise it throws an exception
  • In try block if exception occurs than expression after printScore() method call will never executed
  • The catch block is executed in-case exception is occurred in respective try block
  • At the last finally block will always get executed

Handling multiple exceptions from Scala


Important rules for Scala exception handling

  • In Scala, all exceptions are unchecked exceptions (no Checked Exception like Java)
  • Exception catch block uses pattern matching to handle exceptions
  • If you have declared finally block, it will always be executed whether exception is thrown from try block or not
  • In order to handle the exception, you must have try block followed by catch and/or finally blocks
  • You can use either finally block or catch block or both along with try block
  • As mentioned in my post regarding Scala data types, throw expression has return type Nothing


Leave a Reply

Notify of