×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

How to throw exception in Scala?

By IncludeHelp Last updated : November 15, 2024

Exceptions in Scala

Exceptions are cases or events that occur in the program at run time and hinder the regular flow of execution of the program. These can be handled in the program itself.

Scala also provides some methods to deal with exceptions.

When the program's logic is probable to throw an exception, it has to be declared that such an exception might occur in the code, and a method has to be declared that catches the exception and works upon it.

How to throw exception?

In Scala, the throw keyword is used to throw an exception and catch it. There are no checked exceptions in Scala, so you have to treat all exceptions as unchecked exceptions.

Also read, Java | checked and unchecked exceptions

Syntax

throw exception object

To throw an exception using the throw keyword we need to create an exception object that will be thrown.

Example 1

In this example, we will throw an exception if the speed will be above 175KmpH.

object MyObject {
    // Function to check speed and throw exception if speed exceeds the limit
    def checkSpeed(speed: Int): Unit = {
        if (speed > 175)
            throw new ArithmeticException("The rider is going over the speed limit!")
        else 
            println("The rider is safe under the speed limit.")
    }

    // Main method to call checkSpeed with exception handling
    def main(args: Array[String]): Unit = {
        try {
            checkSpeed(200)  // Example call to check speed
        } catch {
            case e: ArithmeticException => 
                println(s"Exception: ${e.getMessage}")
        }
    }
}

Output

Exception: The rider is going over the speed limit!

Explanation

In the above code, we have declared a function checkSpeed() that takes the speed of the bike and check if it’s above the speed limit which is 175. If the speed is above 175 it throws an Arithmetic exception that says "The rides is going above the speed limit!!!". Else it prints "The rider is safe under the speed limit".

Example 2

In this example, we will learn to throw an exception and catch it using the try-catch block.

object MyObject {
    // Function to throw an exception for invalid username
    def isValidUname(name: String): Unit = {
        throw new Exception("The user name is not valid!")
    }

    // Main method to call isValidUname with exception handling
    def main(args: Array[String]): Unit = {
        try {
            isValidUname("Shivang10")  // Example username
        } catch {
            case ex: Exception => 
                println("Exception caught: " + ex.getMessage)  // Catch and print exception message
        }
    }
}

Output

Exception caught: The user name is not valid!

Explanation

In the above code, we have a function isValidUname() that throws an exception which is caught by the catch block in the main function.

Comments and Discussions!

Load comments ↻





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