×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala catchAll Object

By IncludeHelp Last updated : November 15, 2024

Scala being a scalable programming language has good support for all types of things. In exception handling also scala has many methods defined to do advanced things in error handling.

One of advanced method that is supported by Scala is the catchAll object.

catchAll Object

The catchAll object is the object that can catch all types of exceptions in the program. This object is used when we do not know what type of exception will be thrown.

Syntax to define the working of Scala catchAll object

allCatch.opt(1.toInt)
res10: Option[Int] = Some(1)

Handling Exceptions with allCatch

This example demonstrates how to handle exceptions functionally using allCatch.opt:

import scala.util.control.Exception.allCatch

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

    // Catch division result or failure
    val result = allCatch.opt(5 / (i - j))
    result match {
      case Some(value) => println(s"Division result: $value")
      case None => println("Arithmetic exception.")
    }

    // Catch invalid string to integer conversion
    val stringToInt = allCatch.opt("a".toInt)
    stringToInt match {
      case Some(value) => println(s"Converted string: $value")
      case None => println("Invalid string for conversion.")
    }

    // Another division attempt with error handling
    val divisionResult = allCatch.opt(5 / (i - j))
    divisionResult match {
      case Some(value) => println(s"Division result: $value")
      case None => println("Error: Division by zero.")
    }

    // Finally block message
    println("The finally block runs always...")
  }
}

Output

Arithmetic exception.
Invalid string for conversion.
Error: Division by zero.
The finally block runs always...

Comments and Discussions!

Load comments ↻





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