Scala Exceptions – Scala Exception Handling and Throw Keyword

Free Scala course with real-time projects Start Now!!

Today, we will discuss Scala Exceptions and Exceptions Handling. We will also learn about the Scala Try-Catch Blocks and the Throws Keyword in Scala. Along with this, we will cover Scala Finally Block and Scala Exception Handling.

There may be situations your code may misfunction when you run it. These abnormal conditions may cause your program to terminate abruptly. Such runtime errors are called exceptions.

So, let’s start the Scala Exception Tutorial.

Scala Exceptions - Scala Exception Handling and Throw Keyword

Scala Exceptions – Scala Exception Handling and Throw Keyword

Introduction to Scala Exceptions

All Scala Exceptions are unchecked. This is unlike Java, where exceptions are either checked or unchecked. Here, even SQLException and IOException are unchecked. So, let’s begin with the Exceptions in Scala. I also recommend you to go through our article on Scala Job Opportunities after reading this article.

Scala Exception Example

Take a look at the following Scala Exception example. We declare a function to divide two integers and return the result.

scala> def div(a:Int,b:Int):Float={
    | a/b}
div: (a: Int, b: Int)Float

Now, let’s call it.

scala> div(1,0)
java.lang.ArithmeticException: / by zero
 at .div(<console>:12)
 ... 28 elided

As you can see, this raises an Arithmetic Exception in Scala.

Learn: Scala Environment Setup and get Started with IDE

Scala Try-Catch Blocks

When we suspect that a line or a block of code may raise an exception in Scala, we put it inside a try block. What follows is a catch block. We can make use of any number of Try-Catch Blocks in a program.

Here’s how we would deal with the above situation:

scala> def div(a:Int,b:Int):Float={
    | try{
    | a/b
    | }catch{
    | case e:ArithmeticException=>println(e)
    | }
    | 0
    | }
div: (a: Int, b: Int)Float
scala> div(1,0)
java.lang.ArithmeticException: / by zero
res1: Float = 0.0

a. Another Example

Let’s take another example of Scala Exception Handling:

scala> def func(n:Int){
    | try{
    | print(1/n)
    | var arr=Array(1,4)
    | arr(17)
    | }catch{
    | case e:ArithmeticException=>println(e)
    | case anon:Throwable=>println("Unknown exception: "+anon)
    | }
    | }
func: (n: Int)Unit
scala> func(1)

Unknown exception: java.lang.ArrayIndexOutOfBoundsException: 17

Throwable is a super class in the exception hierarchy. So, if we want our code to be able to handle any kind of exception, we use Throwable.

Learn: Scala Control Structures

Scala Finally Block

Imagine, if you’re working with a resource and an exception occurs in the middle. You still haven’t released the resource. This could be a file, a network connection, or even a database connection. To deal with such a situation, we have the Finally Block. We can release all resources in this block. Well, whether an exception happens in your code or not, the code under ‘finally’ will run, no matter what.

Let’s take the example of our function for division here:

scala> def func(a:Int,b:Int):Float={
    | try{
    | a/b}
    | catch{
    | case e:ArithmeticException=>println(e)
    | }
    | finally{
    | println("This will print no matter what")
    | }
    | 0
    | }
func: (a: Int, b: Int)Float
scala> func(1,0)
java.lang.ArithmeticException: / by zero

This will print no matter what
res4: Float = 0.0

Scala Throw Keyword

We can also explicitly throw a Scala exception in our code. We use the Throw Keyword for this. Let’s create a custom exception.
In Jewish culture, Bat Mitzvah is coming with age ceremony with age 12 for young boys.

scala> def batmitzvah(age:Int){
    | if(age<12){
    | throw new Exception("Sorry, you're ineligible yet")
    | }
    | else{ println("Eligible")}
    | }
batmitzvah: (age: Int)Unit
scala> batmitzvah(10)
java.lang.Exception: Sorry, you're ineligible yet
 at .batmitzvah(<console>:13)
 ... 28 elided
scala> batmitzvah(13)

Eligible

The Throws Keyword

When we know that certain code throws an exception in Scala, we can declare that to Scala. This helps the caller function handle and enclose this code in Try – Catch Blocks to deal with the situation. We can either use the throws keyword or the throws annotation.

@throws(classOf[NumberFormatException])
def validateit()={
"abcd".toInt
}
Here’s another example:
@throws[IOException]("if the file doesn't exist")
def read() = in.read()

So, this was all about Scala Exceptions. Hope you like our explanation.

Conclusion

Now, after going through this Scala Exception Tutorial, you have the understanding of how to deal with your code and what it does when you run it. Stay tuned for more with Scala.

Furthermore, if you have any query, feel free to ask in the comment Section.

For Reference

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

No Responses

  1. Chandresh Bhatt says:

    Thanks for @throws annotation.

Leave a Reply

Your email address will not be published. Required fields are marked *