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 similiar. 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
throw exception object Example: throw new ArthematicException("divide by 0")
val x =
if (n % 10 == 0)
throw new RunTimeException(“n must be a multiple of 10”)
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:
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.
Exception caught in main: java.lang.Exception: Exception thrown from func
- Scala this keyword
- Scala | yield Keyword
- Catch and Throw Exception In Ruby
- PHP | var keyword
- Global keyword in Python
- How to implement is functionality without using is keyword in C#
- Invoking an overloaded constructor using this keyword in C#
- Scala Tutorial – Learn Scala with Step By Step Guide
- Scala | Either
- Set in Scala | Set-1
- Scala Map
- Set in Scala | Set-2
- Stack in Scala
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.