Exceptions in your code, catching them the best way [Java and Scala overlap]

Table of contents
Reading Time: 3 minutes

Hey folks, hope everyone is enjoying their coding days ( or nights whichever you prefer 😛 ) . If you have been redirected here from your browser then you are probably finding a better or cleaner way to make your Scala code robust and readable altogether.

Recently I have been going through some Scala code written by a majority of Java developers who would like to learn Scala and are fairly new to the language. I hope this blog helps them as well and they also learn something new from it.

We would take a brief look at the ways of dealing with exceptions in our Scala applications, in a pair of blogs. This blog lets you use your existing knowledge of Java in Scala programs with a bit of a twist, its not really big on functional way that we follow but the next blog would be more focused on the functional aspect of Scala to achieve the same results.

So here we would see some common practices that we used to follow from the conventional world of Java and then we would see how we do same thing in Scala and the benefits we get from this new way [ the Scala way 😉 ].

Suppose there is a piece of code in our application that could generate an exception, also we don’t want it to affect the behavior of our application adversely, then the obvious choice for us to handle it in Java was to wrap this piece of code in a try-catch block.

Scala code depicting this way of handling exceptions in our application would be something like this :

try {

  info("Calling method that could generate the exception")
  riskyCodeInvoked("Exception Expected in certain cases")

} catch {

  case ex: Exception =>
    error("Exception occurred and successfully caught", ex)
    handlerMethod(ex) // used to handle the exceptions



The above code looks alright and functions well too, isn’t it ? So is there anything wrong with this code snippet ? Actually there is one problem which is not apparent while just looking at or dry running this code.

The above code would also catch any critical or fatal exception such as VirtualMachineError which includes OutOfMemoryError and other fatal errors.

These fatal errors should rather be passed to JVM directly. These exceptions are handled by JVM at low level and are mostly recovered by restarting the JVM. Handling these errors in your code could lead to an infinite loop where same error could occur again and again as JVM is not recovering from it.

This is a very common problem and must always be avoided in code. Fortunately Scala provides a rather simple way to avoid this issue, we can do it like this :


info("Calling method that could generate the exception")

riskyCodeInvoked("Exception Expected in certain cases")


case NonFatal(ex) =>
  ex match {
    case ex:ArithmeticException => error("Arithmetic exception",ex)
    case _ => error("some other exception", ex)


Now this modified code would only be handling all non fatal exceptions, in case some fatal exception occur it will be passed directly to and caught by JVM.

Although above approach is good enough to use in your application, but when there are large number of lines in your code and you simply cannot write all that logic in one single method, you should rather try to divide your logic in many small private methods and compose them in such a way that it does not reduce the readability of your code.

Writing several methods with try-catch block, like we used to do in traditional Java code would simply be polluting your programs with boilerplate code. Wouldn’t it be nice if you could create a pipeline with your code and every method in the pipeline would simply be responsible for either returning a valid result or an exception. This would allow you to handle the exception only once and at the level when you first called the composed method.

We would see how to create such a composition of methods in my next blog. So stay tuned guys and let’s keep coding the best that we can.


Written by 

Rachel Jones is a Solutions Lead at Knoldus Inc. having more than 22 years of experience. Rachel likes to delve deeper into the field of AI(Artificial Intelligence) and deep learning. She loves challenges and motivating people, also loves to read novels by Dan Brown. Rachel has problem solving, management and leadership skills moreover, she is familiar with programming languages such as Java, Scala, C++ & Html.

3 thoughts on “Exceptions in your code, catching them the best way [Java and Scala overlap]3 min read

Comments are closed.