Scala | Exception Handling
Last Updated : 15 Nov, 2019
What is an Exception?
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time. These events change the flow control of the program in execution. These are situations that are not too dangerous and can be handled by the program.
Exception Hierarchy
All exception and errors types are sub classes of class
Throwable, which is base class of hierarchy. One branch is headed by
Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. Another branch,
Error are used by the Java run-time system(
JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error.
Exceptions in Scala
Exception handling in Scala is implemented differently, but it behaves exactly like Java and works seamlessly with existing Java libraries. In scala, All exceptions are
unchecked. there is no concept of checked exception Scala facilitates a great deal of flexibility in terms of the ability to choose whether to catch an exception.
Note: At compile time “checked” exceptions are checked In Java . If a method might throw an
IOException, we must declare it.
How does Scala Exception Work?
Exceptions in scala work the same way as in C++ or Java. When an exception occurs, say an ArithmeticException as shown in the previous example the current operation is aborted, and the runtime system looks for an exception handler that can accept an ArithmeticException. Control resumes with the innermost such handler. If no such handler exists, the program terminates.
The Throwing Exceptions Throwing an exception. It looks same as in Java. we create an exception object and then we throw it by using throw keyword.
Syntax: throw new ArithmeticException
The try/catch Construct The try/catch construct is different in Scala than in Java, try/catch in Scala is an
expression. The exception in Scala and that results in a value can be pattern matched in the catch block instead of providing a separate catch clause for each different exception. Because try/catch in Scala is an expression. Here is an example of exception Handling using the conventional try-catch block in Scala.
Scala // Scala program of try-catch Exception import java.io.IOException // Creating object object GFG { // Main method def main(args:Array[String]) { try { var N = 5/0 } catch { // Catch block contain cases. case i: IOException => { println("IOException occurred.") } case a : ArithmeticException => { println("Arithmetic Exception occurred.") } } } }
Output: Arithmetic Exception occurred.
In Scala a single catch block can handle all kinds of exceptions thus providing flexibility.
The finally Clause : If we want some part of our code to execute irrespective of how the expression terminates we can use a finally block. Here is an example of the above:
Scala // Scala program of finally Exception // Creating object object GFG { // Main method def main(args: Array[String]) { try { var N = 5/0 } catch { // Catch block contain case. case ex: ArithmeticException => { println("Arithmetic Exception occurred.") } } finally { // Finally block will execute println("This is final block.") } } }
Output: Arithmetic Exception occurred. This is final block.
Similar Reads
Exception handling in Julia
Any unexpected condition that occurs during the normal program execution is called an Exception. Exception Handling in Julia is the mechanism to overcome this situation by chalking out an alternative path to continue normal program execution. If exceptions are left unhandled, the program terminates
6 min read
Scala | Finally Exceptions
Scala finally block is used to execute important code such as closing connection, stream or releasing resources( it can be file, network connection, database connection etc). It will be always executed not matter if an exception is thrown or not. The finally block will be executed after the try and
3 min read
Spring MVC - Exception Handling
Prerequisites: Spring MVC When something goes wrong with your application, the server displays an exception page defining the type of exception, the server-generated exception page is not user-friendly. Spring MVC provides exception handling for your web application to make sure you are sending your
6 min read
Exception Handling in Programming
Exception handling is a critical aspect of programming, enabling developers to manage unexpected or erroneous situations gracefully. In this article, we'll discuss the concept of exception handling, its importance, and best practices for implementing it effectively in various programming languages.
7 min read
Exception handling in Objective-C
Exception handling is an essential aspect of Objective-C programming, enabling developers to manage unforeseen errors effectively. Objective-C provides a robust set of tools and methodologies to handle exceptions, ensuring the stability and reliability of applications. Let's delve deeper into the nu
5 min read
File Handling in Scala
File Handling is a way to store the fetched information in a file. Scala provides packages from which we can create, open, read and write the files. For writing to a file in scala we borrow java.io._ from Java because we donât have a class to write into a file, in the Scala standard library. We coul
3 min read
Define Exception handling in ES6
Exception: Exceptions are unwanted event that basically interrupts the normal flow of program. There are two types of exception in general:- Synchronous (eg. runtime errors)Asynchronous (eg. system errors) Exception Handling: Often a times exception happens in a program that causes the program to te
3 min read
Exception Handling in Kotlin Coroutines
Coroutines are a new way for us to do asynchronous programming in Kotlin in Android. When developing a production-ready app, we want to ensure that all exceptions are handled correctly so that users have a pleasant experience while using our app. In this article, we will discuss how to properly hand
7 min read
Exception Handling in Distributed Systems
Exception handling in distributed systems is crucial for maintaining reliability and resilience. This article explores strategies for managing errors across networked services, addressing challenges like fault tolerance, error detection, and recovery, to ensure seamless and robust system operation.
12 min read
Error Handling in MATLAB
Error Handling is the approach of creating a program that handles the exceptions thrown by different conditions without crashing the program. For example, consider the case when you are multiplying two matrices of orders (m x n) and (m x n). Now, anyone who has done elementary linear algebra knows t
2 min read