Scala exception handling LEARNOVITA

Scala Exception Handling Tutorial | Learn in 1 Day [ STEP-IN ]

Last updated on 06th Aug 2022, Blog, Tutorials

About author

Jagan Mohan (Big Data Specialist )

Jagan Mohan provides in-depth presentations on various big data technologies. She specializes in Docker, Hadoop, Microservices, Matlab, and deep understanding of machine learning techniques and algorithms Commvault, and BI tools.

(5.0) | 18967 Ratings 1114

Introduction to Scala Exception Handling:

In this tutorial, we’re about to observe exception handling in Scala. We’ll explore alternative routes of handling them, exploiting completely totally different constructs provided by the language.

What’s Associate in Nursing Exception?

An exception is a happening that changes the traditional flow of a program.

Exception handling is the mechanism to reply to the incidence of associate exception.

Exceptions are also checked or unchecked. Scala only permits unchecked exceptions, though. This implies that, at compile-time, we’ve got a bent to not being able to acknowledge if a way is throwing an Associate in Nursing associated exception we’ve got a bent to not appear to be handling.

A Basic Calculator:

Let’s write a straightforward calculator to illustrate alternative routes of handling exceptions in Scala. It’ll only add positive number numbers:

  • object CalculatorExceptions class IntOverflow Exception extends Runtime Exception
  • category NegativeNumberException extends RuntimeException
  • }
  • object Calculator zero || b < 0) throw new NegativeNumberException
  • val result = a + b
  • if (result < 0) throw new IntOverflowException
  • result
  • }
  • }

Our technique may throw a NegativeNumberException if one in every of the addends is negative, or IntOverflowException if the add overflows the Int vary. Once exploiting our calculator, we’ll need to take under consideration some way to handle those exceptions. Within the following paragraphs, we’ll see alternative routes of doing it in Scala.

Try/catch/finally:

A basic manner we’ll handle exceptions in Scala is that the try/catch/finally construct, very virtually just like the Java one.

In the following example, to form testing easier, we’ll return a special negative error code for each exception caught:

  • def tryCatch(a: Int, b: Int): Int = catch finally will forever be invoked
  • println(“Calculation done!”)
  • }
  • }

Some points to notice concerning the on high of example:

The “risky” code goes among the try block, the code among the finally block will forever be dead, in spite of what happens before – this block is handy, as Associate in Nursing example, whenever we tend to want to form sure we’ve got a bent to shut a resource kind of a data affiliation case statements is also utilized within the catch section to match completely totally different exception kinds.

With this syntax, we’re forced to see what to undertake to try and do with the exceptions as shortly as they’re thrown. In our example, we’ve got a bent to come to completely totally different error codes observing the exception we tend to catch.

Try/Success/Failure:

Try[T] could be a math data kind, whose instances are unit Success[T] and Failure[T].

Let’s rewrite our tryCatch technique pattern it:

  • def trySuccessFailure(a: Int, b: Int): attempt[Int] = attempt
  • Now, we’ll use some tests to point but the results of trySuccessFailure is used in AN extremely purposeful style:
  • “trySuccessFailure” need to “handle NegativeNumberException” in “>
  • }
  • it need to “handle IntOverflowException” in “>
  • }
  • it need to “return the proper sum” just in case Success(result) => assert(result == 5)
  • “>
  • }

Our technique will be available in either successful or a Failure class. using a pattern match, we’ll merely handle the results of our performance.

Catch Objects:

The allCatch.withTry object permits America to catch all the exceptions and handle them with an endeavor. The on high of code will behave specifically as a result of the trySuccessFailure we tend to tend to previously enforced .

scala.util.control.Exception in addition provides out-of-the-box like and either to wrap the exception in, severally, AN chance or AN Either.

An interesting feature of catch objects is that the chance of shaping custom matchers. to look at but simple they’re to stipulate, we’ll write one that entirely handles NegativeNumberException:

  • value myCustomCatcher = catching(classOf[NegativeNumberException])
  • Moreover, we’ll use the scala.util.control.Exception.ignoring() catch object to catch and ignore the specified exceptions:
  • def ignoring Sum(a: Int, b: Int) =
  • ignoring(classOf[NegativeNumberException], classOf[IntOverflowException]) up to $”)
  • }
  • Let’s use some tests to point the behavior of our new matcher:
  • “customCatchObjects” need to “handle NegativeNumberException” in “>
  • }
  • it need to “handle IntOverflowException” in
  • }
  • it need to “return the proper sum” just in case Success(result) => assert(result == 5)
  • “>
  • }

It needs to “ignore like exceptions” in. As we’ll see, simply just in case an IntOverflowException exception is thrown, it’ll not be handled.

Catch objects are handy to modify the exception handling logic and avoid unvaried code.

However, they’re less known compared to Try/Success/Failure.

Functional Composability:

Functional Composability in Scala

This is {often|This can be} often essential once we tend to area a unit aiming for purposeful composability.

We can combine our ways that to higher demonstrate but the handling of the exceptions is completed at the tip of the chain:

  • “customCatchObjects composed with trySuccessFailure” have to be compelled to “return the correct sum” just in case Success(result) => assert(result == 8)
  • “>
  • }
  • it have to be compelled to “print AN error” just in case Success(result) => fail(“Should fail!”)
  • “>
  • }

In the code on prime of, we tend to determine what to do to try and do with our exception at the terrible end. Once writing our trySuccessFailure and customCatchObjects, we tend to not have to be compelled to reckon it.

Both Try/Success/Failure and catch objects facilitate note down purposeful composable code. they allow deferring the analysis of the exceptions, instead of managing them promptly as forced by the classical try/catch.

Exception Hierarchy:

All exceptions and errors are unit sub classes of sophistication Throwable, that’s the bottom class of hierarchy. One branch is headed by Exception. This class is utilized for exceptional conditions that user programs have to be compelled to catch. NullPointerException is AN example of such an exception. another branch, the Error area unit utilized by the Java run-time system(JVM) to purpose errors having to do with the run-time setting itself(JRE). StackOverflowError is AN example of such a mistake.

Exception handling in Scala is enforced otherwise, but it behaves specifically like Java and works seamlessly with existing Java libraries. In scala, All exceptions are unit uncurbed. There’s no plan of checked exceptions, Scala facilitates an honest deal of flexibility in terms of the ability to decide on whether or not or to not catch AN exception.

Note: At compile time “checked” exceptions area unit checked In Java . If a method might throw an IOException, we should always declare it.

How will Scala Exceptions Work?

Exceptions in scala work an identical technique as in C++ or Java. Once an exception happens, say AN ArithmeticException as shown at intervals the previous example the current operation is aborted, and thus the runtime system seems for AN exception handler that will accept AN ArithmeticException.

The Throwing Exceptions:

Throwing AN exception. it’s constant as in Java. we’ve got a bent to provide AN exception object thus we’ve got a bent to throw it by victimization.

Syntax:

Throw new ArithmeticException

The try/catch Construct

The try/catch construct is totally totally different in Scala than in Java, try/catch in Scala is AN expression. The exceptions in Scala that find themselves in a very valuable area unit usually pattern matched at intervals the catch block instead of providing a separate catch clause for each fully totally different exception. as a result of try/catch in Scala is AN expression. Here is an example of exception Handling victimization, the standard try-catch block in Scala.

  • // Scala program of try-catch Exception
  • import java.io.IOException
  • // creating object
  • object GFG
  • technique
  • def main(args:Array[String])
  • power unit N = 5/0
  • }
  • catch
  • “>
  • case a : ArithmeticException =>
  • “>
  • }
  • }
  • }

Output:

Arithmetic Exception occurred. In Scala one catch block can handle {all types|all kinds|every kind|every type|all thuisarts} of exceptions so providing flexibility.

The final Clause : If we’d like some part of our code to execute no matter but the expression terminates, we’ll use a finally block.

  • // Scala program of finally Exception
  • // creating object
  • object GFG
  • methodology
  • def main(args: Array[String])
  • catch
  • “>
  • }
  • finally
  • can execute
  • println(“This is final block.”)
  • }
  • }
  • }

Try and Catch Block:

Scala’s exceptions work like exceptions in many different languages like Java. instead of returning a value at intervals the normal methodology, the way can terminate by throwing an associated exception. However, Scala doesn’t even have checked exceptions.

When you would like to handle exceptions, you utilize an attempt catch block like you’d in Java except that the catch block uses matching to identify and handle the exceptions.

Throwing Exceptions:

Throwing associate exceptions seems similar as in Java. You manufacture an associate exception object therefore you throw it with the throw keyword as follows.

Throw new Illegal Argument Exception

Catching Exceptions

Scala permits you to try/catch any exception throughout one block therefore perform pattern matching against its victimization case blocks. try the next example program to handle exceptions.

Example

  • import java.io.FileReader
  • import java.io.FileNotFoundException
  • import java.io.IOException
  • object Demo “> catch “>
  • case ex: IOException => “>
  • }
  • }
  • }
  • Save the upper than program in Demo.scala. The next commands are used to compile and execute this program.
  • Command
  • \>scalac Demo.scala
  • \>scala Demo

Output

Missing file exception

The behavior of this try-catch expression is the same as in different languages with exceptions. The body is dead, associated if it throws an exception, each catch clause is tried in turn.

The finally Clause

You can wrap an associated expression with a finally clause if you want to cause some code to execute nevertheless but the expression terminates. try the next program.

Example

  • import java.io.FileReader
  • import java.io.FileNotFoundException
  • import java.io.IOException
  • object Demo “> catch “>
  • case ex: IOException => “>
  • } finally “>
  • }
  • }

Save the upper than program in Demo.scala. The next commands are used to compile and execute this program.

  • Command
  • \>scalac Demo.scala
  • \>scala Demo
  • Output
  • Missing file exception
  • Exiting finally

Scala Custom Exception:

Scala Custom Exception

In scala, you’ll turn out your own exception. Its victimization is remarked as a custom exception. you wish to increase the Exception class whereas declaring a custom exception class. you’ll turn out your own exception message within the custom class. Let’s examine the associate degree example.

  • Scala Custom Exception Example
  • class InvalidAgeException(s:String) extends Exception(s)
  • class ExceptionExample “>
  • }
  • }
  • Exception Occured : InvalidAgeException : Not eligible

Conclusion:

An exception is associate degree unwanted or stunning events that happen throughout the execution of a program i.e at run time. These events modify the flow management of the program in execution. These squares live things that aren’t too dangerous and could be handled by the program.

Are you looking training with Right Jobs?

Contact Us

Popular Courses