×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala Exceptions

By IncludeHelp Last updated : November 15, 2024

Exceptions

Exception in programming occurs during execution of the program, the error occurs during the execution of the program. This error interrupts the execution sequence of the code. The exceptions are handled using bypassing the code to an exception handler. This handles the exceptions and reduces the occurrence of error.

Scala Exceptions

Exception in Scala has the same working as exceptions of any other programming language but is implemented a bit differently. Scala supports only unchecked exceptions i.e. no checked exception are inbuilt for Scala.

Exceptions are inherited from throwable which also has a subclass of errors. And exceptions have a subclass called unchecked exception which is quite useful in programming.

Scala Exceptions Handling

Exceptions are handled the same way as other programming languages like Java i.e. throwing an exception and then making for a block that catches it.

How does Scala Exception Handling Work?

Suppose an exception occurs in your Scala code. The compiler holds execution and gives the flow to the exception handler, that does its work. And runs the code, otherwise, the program gets terminated.

Scala also uses the try-catch block to handle exceptions. As in java, Scala also uses try block to put the code that can have error and then use catch or finally block to handle the error thrown.

Throwing exceptions in Scala needs the keyword throw which creates an exception object.

Try Catch Block

Scala also uses the try-catch block to handle the exceptions that may arise during the program execution.

Error handling using the try-catch block works in the following manner: the code that may give rise to another is footed in the try block. based on the type of exception the code Code throws the cache log has exception objects that are executed when the exception occurs.

For example, if we place a division in Scala try block and the expression evaluates to two division by zero it throws an arithmetic exception that needs to be handled. so in our Scala catch block, we will define an arithmetic exception that will be caught if an exception occurs and the following code will be executed based on the occurrence of the exception.

Syntax

try{
  //code that may contain an exception. 
}
catch {
  case a : typeOfException =>
    // code to be executed
} 

Example

import java.io.IOException

object MyClass {
  def main(args: Array[String]): Unit = {
    var i = 3
    var j = 3

    try {
      var N = 5 / i - j
      println("The division is successful, the value is: " + 5 / (i - j))
    } catch {
      case e: ArithmeticException =>
        println("Arithmetic exception occurred.")
    }
  }
}

Output

The above code has 2 two outputs based on the value of I and J

case 1 : i= j
Arithmetic exception occurred

case 2 : i !=j
The division is successful the value is -5 

Note: **the value is evaluated based on the value entered in the code 

Try Catch Finally Block

Sometimes in programming, there are cases when the exception occurred is not known to we have chances of being occurred or some exception that it does not have an exception class or a case to catch that. in this case, we will use The Finally keyword in the exception handling. the finally-block is a block of code in error handling that runs when no known exception case is matched i.e. it runs when catching face. the finally-code will ultimately even if there is an error or not. it will run with both cases when the try does not throw an exception, And when they try throws an exception and catch block runs.

Syntax

try{
  //code that may contain an exception. 
}
catch {
  case a : typeOfException =>
  // code to be executed
} 
finally {
  // This block will definitely run
}

Example to show how catch block works?

import java.io.IOException

object MyClass {
  def main(args: Array[String]): Unit = {
    var i = 3
    var j = 3

    try {
      var N = 5 / i - j
      println("The division is successful, the value is: " + 5 / (i - j))
    } catch {
      case e: ArithmeticException =>
        println("Arithmetic exception occurred.")
    } finally {
      println("The finally block runs in all cases...")
    }
  }
}

Output

Arithmetic exception occurred.
The finally code that runs in all cases...

Code logic

The above code is used to display how a finally statement runs when an error has occurred? In the example, we have a try block that contains a divide by zero arithmetic error, this error is then handled using the Scala catch block which prints "arithmetic exception occurred". After the execution of this catch block the finally block is invoked that prints "The Finally code that runs in all cases". After the execution of finally code the program goes back to its original flow.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.