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


    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!!!")
            println("The rider is safe under the speed Limit.")
    def main(args: Array[String]) {


java.lang.ArithmeticException: The rider is going over the speed Limit!!!


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 {
            case ex : Exception => println("Exception caught : " + ex)


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


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

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.