Using Try Catch Finally construct, Scala catches and manages exceptions. In short it is used for exception handling. If you are not aware what “exception” means, it is actually any unexpected behavior that occurs during program execution.

Try: This is the block where the code actually runs and exceptions are thrown.
Catch: This block catches and manages the exceptions.
Finally: This block executes every time, no matter if there is an exception or not.

Let’s see how it works with a simple example.

try{
val a=5
val b=0
a/b
} catch{
case t: Throwable => println("Divide by zero error")
}
finally {
println("In finally")
}
Output:
Divide by zero error
In finally
view raw Example1.sc hosted with ❤ by GitHub

In above code we have assigned values to variables a/b inside TRY block and then divide the variables. As we know from other programming languages this will throw an “Arithmetic Exception”. But the program does not terminate as the exception is caught in CATCH block and the message is printed. And then FINALLY block is executed.

Few more things to notice are:
1.The exception/error received by the Catch block is pattern matched . Hence we can write multiple case statements each handling a different exception/error.
2.Inside Catch we have used ‘t’ which is of type Throwable. This is the parent class which catches all exceptions and errors. We will see few other types in this blog.
3.If variable b had a proper value, then there would be no exception. But, still the finally block would have executed.

Match One or More Exceptions with try/catch

In Scala it is very easy to handle multiple exceptions inside Catch block. All you need to do is add exception types as different case statements. Lets see one example.

try{
opensftpreadfile("location")
} catch{
case e: FileNotFoundException => println("Could not find file.")
case e: IOException => println("IOException during file read")
}
finally {
println("In finally")
}
view raw Example2.sc hosted with ❤ by GitHub

In the above example the method opensftpreadfile tries to access a file in sftp location and then read the file. During this method execution if the file is not found then the error can be handled with “FileNotFoundException” . If there is some issue during file read then it is handled with “IOException”.

Catch all Exceptions using Throwable

Using Throwable we can catch all exceptions and errors. Lets say that it does not matter what the issue is , all you need to do is once the error/exception occurred the code should print “Issue Occurred Hence Existing”. In this case we can use Throwable in case statement so that it handles all scenarios.

try{
opensftpreadfile("location")
} catch{
case e: Throwable => println("Issue Occurred Hence Existing")
}
view raw Example3.sc hosted with ❤ by GitHub

Now in above code no matter what error is thrown it will always be handled in catch block.

Why Handle Multiple Exceptions in Catch

We know now that Throwable can handle all exception, so if Throwable can catch all exception then why do we need to handle them separately? The answer is simple. In case we need to have different action based on the type of issue , then we need to know exactly which exception has occurred. Lets see this with a some pseudo code.

try{
opensftpreadfile("location")
} catch{
case e: FileNotFoundException => functionToGenerateFile()
case e: IOException => sendEmailToSupport()
case e: Throwable => print("Some Error")
}
view raw Example4.sc hosted with ❤ by GitHub

In the above code, if the exception is FileNotFoundException then a function is called which generates the missing file. If it’s an IOException then an email is sent to Support team to look at network related issues. All other exceptions are handled by Throwable which simple prints a message.

Use Try Catch as an Expression

In Scala we can use Try Catch as expressions. What this means is the block can return a result from Try or Catch. Note that Finally block never returns anything. Lets check this with an example.

val x: String =try{
val str = "GOOD"
str.substring(0,12)
} catch{
case e: Throwable => "Some Error"
}
finally {
println("In finally")
}
view raw Example5.sc hosted with ❤ by GitHub

Here if the Try block executes successfully it will return the result of substring computed inside the Try block. If there is some error, like in the code above , then the value in the Catch block is returned. Finally never returns anything.

One more thing to notice is in the above example both the Try and Catch block returns String type . Hence variable x is of Type String. If both the types would have differed then x would be of “Any” type. Try to create this yourself and check what happens when you return an Integer instead of String in Catch block.

Throw an Exception in Scala

We have seen that when an exception occurs it is caught in Catch block and post that the normal execution continues. What if after catching the exception we want to terminate the Job. This can be done using throw keyword. The throw keyword is used to throw exceptions from any block or method. Which means it can be used to throw exception from Try as well as Catch block.

In the code below you can see after the exception has occurred, it is handled in the Catch block and hence “String is short” message is printed. But the job execution doesn’t stop there, it continues and prints the remaining step “Reached this Step” .

try{
val str = "GOOD"
str.charAt(20)
} catch{
case e: Throwable => println("String is short")
}
println("Reached this Step")
Output:
String is short
Reached this Step
view raw Example6.sc hosted with ❤ by GitHub

Now lets see how we can terminate the job run inside catch using the throw keyword.

try{
val str = "GOOD"
str.charAt(20)
} catch{
case e: Throwable => println("String is short")
throw e
}
println("Reached this Step")
Output:
String is short
java.lang.StringIndexOutOfBoundsException: String index out of range: 20
view raw Example7.sc hosted with ❤ by GitHub

Here after “String is short” message is printed an exception is immediately throws and the code execution is stopped.

As pattern matching is used in Catch block you can learn more about it here:

This concludes our Scala Exception handling using Try Catch. I will keep adding to this blog as and when I learn something new.

🙂 kudos for learning something new 🙂

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from UnderstandingBigData

Subscribe now to keep reading and get access to the full archive.

Continue reading