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 ArithmeticException("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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.