Open In App

Throw Keyword in Scala

Last Updated : 23 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The throw keyword in Scala is used to explicitly throw an exception from a method or any block of code.In scala, throw keyword is used to throw exception explicitly and catch it. It can also be used to throw custom exceptions. Exception handling in java and scala are very similar. Except that scala treats all types of exceptions as runtime exceptions only, therefore it doesn’t force us to handle them instead uses pattern matching in catch block. throw is an expression that has a result type nothing in scala. If the result wont actually evaluate to anything we can use it in place of any other expression . 

Important things to remember: 

  • Throw expression has a return type of Nothing.
  • Throw is the keyword used to throw an exception, whereas throws is the keyword used to declare exception.
  • Catch block uses pattern matching to handle exceptions

Syntax:

 throw exception object
Example:
 throw new ArithmeticException("divide by 0") 

Example: 

val x = if (n % 10 == 0) 5 else throw new RuntimeException(“n must be a multiple of 10”)

Explanation: If n is a multiple of 10 then 5 is assigned to x, but if n is not a multiple of 10 then an exception is thrown before x can be initialised to anything at all. Because of which, we can say throw has a value of any kind. In scala, throwing an exception is the same as Java. we create an exception object and then we throw it with the throw keyword: 

Example: 

Scala




// Scala program of throw keyword
 
// Creating object
object Main
{
    // Define function
    def validate(article:Int)=
    
        // Using throw keyword
        if(article < 20
            throw new ArithmeticException("You are not eligible for internship") 
        else println("You are eligible for internship") 
    
     
    // Main method
    def main(args: Array[String])
    {
            validate(22)
    }
}


Output:

You are eligible for internship

In above code, if we have article less than 20 than we get no output. When an error occurs, a scala method can throw an exception instead of returning normally. In the below example, there we observe a single exception that is thrown from a function. 

Scala




// Scala program of throw keyword
 
// Creating object
object GFG
{
    // Main method
    def main(args: Array[String])
    {
     
    try
    {
        func();
         
    }
    catch
    {
        case ex: Exception => println("Exception caught in main: " + ex);
         
    }
    }
     
    // Defining function
    def func()
    {
        // Using throw exception
        throw new Exception("Exception thrown from func");
         
    }
}


Output:

Exception caught in main: java.lang.Exception: Exception thrown from func


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads