Open In App

Scala | Exception Handling

What is an Exception?

An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time. These events change the flow control of the program in execution. These are situations that are not too dangerous and can be handled by the program.

Exception Hierarchy

All exception and errors types are sub classes of class Throwable, which is base class of hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. Another branch, Error are used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error.

Exceptions in Scala

Exception handling in Scala is implemented differently, but it behaves exactly like Java and works seamlessly with existing Java libraries. In scala, All exceptions are unchecked. there is no concept of checked exception Scala facilitates a great deal of flexibility in terms of the ability to choose whether to catch an exception.

Note: At compile time “checked” exceptions are checked In Java . If a method might throw an IOException, we must declare it.

How does Scala Exception Work?

Exceptions in scala work the same way as in C++ or Java. When an exception occurs, say an ArithmeticException as shown in the previous example the current operation is aborted, and the runtime system looks for an exception handler that can accept an ArithmeticException. Control resumes with the innermost such handler. If no such handler exists, the program terminates.

The Throwing Exceptions
Throwing an exception. It looks same as in Java. we create an exception object and then we throw it by using throw keyword.
Syntax:

throw new ArithmeticException

The try/catch Construct
The try/catch construct is different in Scala than in Java, try/catch in Scala is an expression. The exception in Scala and that results in a value can be pattern matched in the catch block instead of providing a separate catch clause for each different exception. Because try/catch in Scala is an expression. Here is an example of exception Handling using the conventional try-catch block in Scala.




// Scala program of try-catch Exception 
import java.io.IOException
  
// Creating object
object GFG
{  
    // Main method
    def main(args:Array[String])
    {  
        try
        {
            var N = 5/0
               
        
        catch 
        {
            // Catch block contain cases. 
            case i: IOException => 
            {
                println("IOException occurred.")
            }
            case a : ArithmeticException => 
            {
                println("Arithmetic Exception occurred.")
            }
   
        }
   
    }  
}  

Output:

Arithmetic Exception occurred.

In Scala a single catch block can handle all kinds of exceptions thus providing flexibility.

The finally Clause :

If we want some part of our code to execute irrespective of how the expression terminates we can use a finally block. Here is an example of the above:




// Scala program of finally Exception 
  
// Creating object
object GFG 
{
    // Main method
    def main(args: Array[String]) 
    {
        try
        {
            var N = 5/0
        
        catch
        {
            // Catch block contain case.
            case ex: ArithmeticException => 
            {
                println("Arithmetic Exception occurred.")
            }
        }
        finally
        {
            // Finally block will execute 
            println("This is final block.")
        }
    }
}

Output:

Arithmetic Exception occurred.
This is final block.

Article Tags :