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
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