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

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

Last updated on 11th Jan 2022, Blog, Tutorials

About author

Priyanka Butt (Big Data Specialist )

Priyanka Butt provides in-depth presentations on various big data technologies. She specializes in Docker, Hadoop, Microservices, Commvault, and BI tools.

(5.0) | 17152 Ratings 1898
  • Introduction to Scala Exception Handling
  • What’s an Exception?
  • A Basic Calculator
  • Try/catch/finally
  • Try/Success/Failure
  • Catch Objects
  • Functional Composability
  • Exception Hierarchy
  • How does Scala Exception Work?
  • Try and Catch Block
  • Scala Custom Exception
  • Conclusion

    Subscribe For Free Demo

    [custom_views_post_title]

      Introduction to Scala Exception Handling:

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


      What’s an Exception?

      an exception is an incident that changes the conventional flow of a program.

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

      Exceptions may be checked or unbridled. Scala solely permits unbridled exceptions, though. this suggests that, at compile-time, we have a tendency to won’t be able to recognize if a technique is throwing an associated exception we have a tendency to don’t seem to be handling.


      A Basic Calculator:

      Let’s write an easy calculator to point out alternative ways of handling exceptions in Scala. It’ll solely add positive whole number numbers:

      • object CalculatorExceptions category IntOverflowException extends RuntimeException
      • 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 might throw a NegativeNumberException if one among the addends is negative, or IntOverflowException if the add overflows the Int vary. When exploiting our calculator, we’ll have to take into account a way to handle those exceptions. In the following paragraphs, we’ll see alternative ways of doing it in Scala.


      Try/catch/finally:

      A basic manner we will handle exceptions in Scala is that the try/catch/finally construct, extremely almost like the Java one.

      In the following example, to create testing easier, we’ll come back a special negative error code for every exception caught:

      • def tryCatch(a: Int, b: Int): Int = {
      • try {
      • come back Calculator.sum(a,b)
      • } catch finally can forever be invoked
      • println(“Calculation done!”)
      • }
      • }

      Some points to note regarding the on top of example:

    • The “risky” code goes within the strive block, the code within the finally block can forever be dead, in spite of what happens before – this block is handy, as an example, whenever we wish to create certain we have a tendency to shut a resource sort of a info affiliation case statements may be employed in the catch section to match totally different exception sorts.
    • With this syntax, we’re forced to determine what to try to do with the exceptions as shortly as they’re thrown. In our example, we have a tendency to return totally different error codes looking at the exception we caught.

    • Try/Success/Failure:

      Try[T] is a pure mathematics knowledge kind, whose instances are unit Success[T] and Failure[T].

      Let’s rewrite our tryCatch technique mistreatment it:

      • def trySuccessFailure(a: Int, b: Int): attempt[Int] = Try
      • Now, we will use some tests to indicate however the results of trySuccessFailure is employed in an exceedingly purposeful style:
      • “trySuccessFailure” ought to “handle NegativeNumberException” in “>
      • }
      • it ought to “handle IntOverflowException” in “>
      • }
      • it ought to “return the right sum” in case Success(result) => assert(result == 5)
      • “>
      • }

      Our technique can come in either a Success or a Failure category. employing a pattern match, we will simply handle the results of our performance.


      Catch Objects:

      Another way of catching exceptions comes from the scala.util.control.Exception object. Let’s use a catch object to handle our Calculator.sum:

      def catchObjects(a: Int, b: Int): Try[Int] = allCatch.withTry

      The allCatch.withTry object permits America to catch all the exceptions and handle them with an attempt. The on top of code can behave specifically because the trySuccessFailure we tend to antecedently enforced.

      scala.util.control.Exception additionally provides out-of-the-box prefer and either to wrap the exception in, severally, an possibility or an Either.

      An interesting feature of catch objects is that the risk of shaping custom matchers. to examine however easy they’re to outline, we will write one that solely handles NegativeNumberException:


      • value myCustomCatcher = catching(classOf[NegativeNumberException])
      • def customCatchObjects(a: Int, b: Int): Try[Int] = myCustomCatcher.withTry
      • Moreover, we will use the scala.util.control.Exception.ignoring() catch object to catch and ignore the desired exceptions:
      • def ignoringandSum(a: Int, b: Int) =
      • ignoring(classOf[NegativeNumberException], classOf[IntOverflowException]) up to $”)
      • }
      • This will execute the pass block of code whereas ignoring the mentioned exceptions.

      Let’s use some tests to indicate the behavior of our new matcher:

      • “customCatchObjects” ought to “handle NegativeNumberException” in “>
      • }
      • it ought to “handle IntOverflowException” in
      • }
      • it ought to “return the right sum” in case Success(result) => assert(result == 5)
      • “>
      • }

      It ought to “ignore such as exceptions” in. As we will see, just in case an IntOverflowException exception is thrown, it’ll not be handled.

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

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


      Course Curriculum

      Learn Advanced Scala Certification Training Course to Build Your Skills

      Weekday / Weekend BatchesSee Batch Details

      Functional Composability:

      So far, we’ve been able to defer the handling of the exceptions to a later stage. This is often essential once we are a unit aiming for purposeful composability.

      We can mix our ways to higher demonstrate however the handling of the exceptions is done at the tip of the chain:

      • “customCatchObjects composed with trySuccessFailure” ought to “return the right sum” in case Success(result) => assert(result == 8)
      • “>
      • }
      • it ought to “print an error” in case Success(result) => fail(“Should fail!”)
      • “>
      • }

      In the code on top of, we tend to decide what to try to do with our exception at the terrible finish. once writing our trySuccessFailure and customCatchObjects, we tend to didn’t need to deem it.

      Both Try/Success/Failure and catch objects facilitate jotting down purposeful composable code. they permit deferring the analysis of the exceptions, rather than managing them right away as forced by the classical try/catch.


      Exception Hierarchy:

    • All exceptions and errors sorts are unit sub categories of sophistication Throwable, that is the base category of hierarchy. One branch is headed by Exception. This category is employed for exceptional conditions that user programs ought to catch. NullPointerException is an example of such an exception. another branch, the Error are employed by the Java run-time system(JVM) to point errors having to do with the run-time setting itself(JRE). StackOverflowError is an example of such a slip.
    • Exception handling in Scala is enforced otherwise, however it behaves specifically like Java and works seamlessly with existing Java libraries. In scala, All exceptions are unbridled. There’s no idea of checked exceptions, Scala facilitates a good deal of flexibility in terms of the power to settle on whether or not to catch an exception.
    • Note: At compile time “checked” exceptions are checked In Java . If a technique would possibly throw an IOException, we should declare it.

    • Course Curriculum

      Get JOB Oriented Scala Training for Beginners By MNC Experts

      • Instructor-led Sessions
      • Real-life Case Studies
      • Assignments
      Explore Curriculum

      How does Scala Exception Work?

      Exceptions in scala work a similar method as in C++ or Java. Once an exception happens, say an ArithmeticException as shown within the previous example the present operation is aborted, and therefore the runtime system appears for an exception handler that may settle for an ArithmeticException. management resumes with the innermost such handler. If no such handler exists, the program terminates.


      The Throwing Exceptions:

      Throwing an exception. it’s the same as in Java. we have a tendency to produce an exception object so we have a tendency to throw it by using.

      Syntax:

      • throw new ArithmeticException
      • The try/catch Construct
      • The try/catch construct is completely different in Scala than in Java, try/catch in Scala is an expression. The exceptions in Scala which end up in a price are often pattern matched within the catch block rather than providing a separate catch clause for every completely different exception. as a result of try/catch in Scala is an expression. Here is an example of exception Handling using, the traditional try-catch block in Scala.
      • // Scala program of try-catch Exception
      • import java.io.IOException
      • // making 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 will handle all types of exceptions so providing flexibility.

      The finally Clause : If we would like some part of our code to execute regardless of however the expression terminates we will use a finally block. Here is an example of the above:

      • // Scala program of finally Exception
      • // making 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 several alternative languages like Java. rather than returning a price within the traditional method, a way will terminate by throwing an exception. However, Scala does not even have checked exceptions.

      When you wish to handle exceptions, you utilize a try catch block such as you would in Java except that the catch block uses matching to spot and handle the exceptions.


      Throwing Exceptions:

      Throwing an exception appears similar as in Java. You produce an exception object so you throw it with the throw keyword as follows.

    • throw new IllegalArgumentException
    • Catching Exceptions
    • Scala permits you to try/catch any exception during a single block so perform pattern matching against it using case blocks. strive the subsequent example program to handle exception.


      • Example
      • import java.io.FileReader
      • import java.io.FileNotFoundException
      • import java.io.IOException
      • object Demo “> catch “>
      • case ex: IOException => “>
      • }
      • }
      • }
      • Save the higher than program in Demo.scala. the subsequent commands are wont 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 alternative languages with exceptions. The body is dead, and if it throws an exception, every catch clause is tried successively.
      • The finally Clause
      • You can wrap an expression with a finally clause if you wish to cause some code to execute notwithstanding however the expression terminates. strive the subsequent program.
      • Example
      • import java.io.FileReader
      • import java.io.FileNotFoundException
      • import java.io.IOException
      • object Demo “> catch “>
      • case ex: IOException => “>
      • } finally “>
      • }
      • }
      • Save the higher than program in Demo.scala. the subsequent commands are wont to compile and execute this program.
      • Command
      • \>scalac Demo.scala
      • \>scala Demo
      • Output
      • Missing file exception
      • Exiting finally

      Scala Custom Exception:

      In scala, you’ll produce your own exception. it’s using referred to as custom exceptions. you want to extend the Exception category whereas declaring a custom exception category. you’ll produce your own exception message in the custom category. Let’s examine an example.


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

      Conclusion:

      An exception is an associate degree unwanted or surprising event that happens throughout the execution of a program i.e at run time. These events modify the flow management of the program in execution. These squares measure things that aren’t too dangerous and might be handled by the program.


      Scala Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

      In this article, we tend to talk regarding Scala’s support for exception handling. When selecting between catch objects and Try/Success/Failure, the trade-off is between code accessibility and code reusability. In Scala, they’re definitively desirable to try/catch/finally since they supply a better thanks to reach purposeful composability.


    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free