Scala Tutorial

Basics

Control Statements

OOP Concepts

Parameterized - Type

Exceptions

Scala Annotation

Methods

String

Scala Packages

Scala Trait

Collections

Scala Options

Miscellaneous Topics

Throw Keyword in Scala

In Scala, the throw keyword is used to raise or throw exceptions, similar to its usage in many other programming languages. Throwing an exception means signaling the runtime that an abnormal condition has occurred. This stops the normal flow of the program, and the runtime starts searching for the nearest catch clause that can handle the exception.

Basic Usage:

  • Throwing an Exception:

You can use the throw keyword followed by an exception object:

def validateAge(age: Int): Unit = {
  if (age < 0) {
    throw new IllegalArgumentException("Age cannot be negative!")
  }
}

When the function is called with a negative age, it will throw an IllegalArgumentException.

  • Catching an Exception:

You can use a try-catch-finally block to catch and handle exceptions:

try {
  validateAge(-5)
} catch {
  case e: IllegalArgumentException => println(e.getMessage)
  case _: Exception => println("An unknown error occurred.")
} finally {
  println("This always runs, whether an exception was thrown or not.")
}

In this example, the "Age cannot be negative!" message will be printed, followed by "This always runs, whether an exception was thrown or not."

Points to Note:

  • In Scala, the try-catch-finally construct is an expression, meaning it returns a value. You can assign the result of this expression to a variable.

  • Scala's catch clause uses pattern matching. This makes it flexible to catch and handle multiple types of exceptions in different ways.

  • While it's possible to throw exceptions, it's idiomatic in many functional programming scenarios to avoid them for error handling. Instead, consider using types like Option, Either, or other monads that can represent failure without throwing exceptions.

  1. Scala throw keyword example:

    • Description: The throw keyword in Scala is used to explicitly throw an exception. It interrupts the normal flow of execution and transfers control to an exception handler.
    • Code:
      // Example using throw keyword
      val divisor = 0
      
      try {
        if (divisor == 0) {
          throw new ArithmeticException("Division by zero")
        }
        val result = 10 / divisor
        println(s"Result: $result")
      } catch {
        case ex: ArithmeticException => println(s"Exception: ${ex.getMessage}")
      }
      
  2. Exception handling with throw in Scala:

    • Description: Exception handling with throw involves throwing an exception in response to a specific condition and catching it in an appropriate exception handler.
    • Code:
      // Exception handling with throw
      val age = -5
      
      try {
        if (age < 0) {
          throw new IllegalArgumentException("Age cannot be negative")
        }
        println(s"Age: $age")
      } catch {
        case ex: IllegalArgumentException => println(s"Exception: ${ex.getMessage}")
      }
      
  3. How to use throw in Scala for custom exceptions:

    • Description: Custom exceptions can be created by extending the Exception class, and instances of these exceptions can be thrown using the throw keyword.
    • Code:
      // Custom exception
      class CustomException(message: String) extends Exception(message)
      
      // Throwing custom exception
      try {
        throw new CustomException("This is a custom exception")
      } catch {
        case ex: CustomException => println(s"Custom Exception: ${ex.getMessage}")
      }
      
  4. Scala throw vs throw new:

    • Description: Both throw and throw new are used to throw exceptions in Scala. throw new is commonly used to instantiate and throw exceptions, while throw is used to throw existing exceptions or errors.
    • Code:
      // Using throw new
      try {
        throw new RuntimeException("This is an exception")
      } catch {
        case ex: RuntimeException => println(s"Exception: ${ex.getMessage}")
      }
      
      // Using throw
      try {
        throw new IllegalArgumentException("Invalid argument")
      } catch {
        case ex: IllegalArgumentException => println(s"Exception: ${ex.getMessage}")
      }
      
  5. Handling checked exceptions with throw in Scala:

    • Description: Checked exceptions (those extending Exception) can be thrown and caught using the throw keyword in Scala.
    • Code:
      // Handling checked exception with throw
      def riskyOperation(): Unit = {
        throw new IOException("File not found")
      }
      
      try {
        riskyOperation()
      } catch {
        case ex: IOException => println(s"IOException: ${ex.getMessage}")
      }
      
  6. Throwing multiple exceptions in Scala:

    • Description: Multiple exceptions can be thrown in different branches of code, and each type of exception can be caught separately.
    • Code:
      def processInput(input: String): Unit = {
        if (input == null) {
          throw new NullPointerException("Input cannot be null")
        } else if (input.isEmpty) {
          throw new IllegalArgumentException("Input cannot be empty")
        } else {
          println(s"Processing input: $input")
        }
      }
      
      try {
        processInput(null)
      } catch {
        case ex: NullPointerException => println(s"NullPointerException: ${ex.getMessage}")
        case ex: IllegalArgumentException => println(s"IllegalArgumentException: ${ex.getMessage}")
      }
      
  7. Throwing non-fatal exceptions in Scala:

    • Description: Non-fatal exceptions, such as those extending RuntimeException, can be thrown using throw. These exceptions do not require explicit handling.
    • Code:
      // Throwing non-fatal exception
      try {
        throw new RuntimeException("This is a non-fatal exception")
      } catch {
        case ex: RuntimeException => println(s"Non-fatal Exception: ${ex.getMessage}")
      }