How to throw exception in Scala?

Scala Exceptions: Here, we are going to learn how to throw exception in Scala? How to declare that a Scala method can throw an exception?
Submitted by Shivang Yadav, on May 16, 2020

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 {
    def checkSpeed(speed : Int ) = {
        if (speed > 175)
            throw new ArithmeticException("The rider is going over the speed Limit!!!")
        else 
            println("The rider is safe under the speed Limit.")
    }
    
    def main(args: Array[String]) {
        checkSpeed(200)
    }
}

Output:

java.lang.ArithmeticException: 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 {
    def isValidUname(name : String ) = {
        throw new Exception("The user name is not valid!")
    }
    
    def main(args: Array[String]) {
        try {
            isValidUname("Shivang10");
        }
        catch{
            case ex : Exception => println("Exception caught : " + ex)
        }
    }
}

Output:

Exception caught : java.lang.Exception: The user name is not valid!

Exception:

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.