Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2020-10-08 08:17:28 Viewed : 1031
Scala try catch and finally
In Scala, you can use try
, catch
, and finally
blocks to handle exceptions and perform cleanup operations. These constructs are similar to those found in many other programming languages. Here is how they work in Scala:
1. try
block: The try
block contains the code that might throw an exception. If an exception occurs within the try
block, it will be caught by the corresponding catch
block (if defined).
2. catch
block: The catch
block is used to handle exceptions that are thrown within the try
block. You can specify the type of exception you want to catch and define how to handle it.
3. finally
block: The finally
block is optional and used for cleanup code that should be executed regardless of whether an exception occurred or not. This block is often used to release resources or perform other necessary cleanup tasks.
Here is a simple example of using try
, catch
, and finally
in Scala:
scalaimport java.io._ object ExceptionHandlingExample { def main(args: Array[String]): Unit = { var file: FileWriter = null try { // Attempt to open a file for writing file = new FileWriter("example.txt") file.write("Hello, Scala!") } catch { case e: IOException => println(s"An IO exception occurred: ${e.getMessage}") case _: Throwable => println("An unexpected error occurred.") } finally { // Close the file regardless of success or failure if (file != null) { file.close() } } } }
In this example:
try
block.IOException
occurs (e.g., if the file cannot be created or written to), we catch it and print an error message.case
for any other unexpected exceptions.finally
block, we ensure that the file is closed, whether or not an exception occurred.The finally
block guarantees that the cleanup code is executed, making it useful for resource management.
Note that Scala allows you to use a try
block without a catch
block if you only want to ensure that the finally
block is executed for cleanup purposes. For example:
scalaimport java.io._ object FinallyExample { def main(args: Array[String]): Unit = { var file: FileWriter = null try { file = new FileWriter("example.txt") file.write("Hello, Scala!") } finally { // Close the file in all cases if (file != null) { file.close() } } } }
In this case, if an exception occurs, it will be propagated, but the finally
block still gets executed.
Similar to Java, but its syntax is consistent with match expressions:
try {
writeToFile(text)
} catch {
case
fnfe: FileNotFoundException => println(fnfe)
case
ioe: IOException => println(ioe)
}
Example:
Following
example illustrates about Scala try catch and finally
Save the file as − TryCatchFinallyEx.scala
TryCatchFinallyEx.scala
package runnerdev
class ExceptionExample {
def divide(x: Int, y: Int) = {
try {
x / y
} catch {
case e: ArithmeticException
=> println(e.printStackTrace())
case ex: Exception => println(ex)
case th: Throwable => println("found a
unknown exception" + th)
} finally {
println("Finaly block
always executes")
}
println("Rest of the
code is executing ")
}
}
object TryCatchFinallyEx {
def main(args: Array[String]) {
var e = new ExceptionExample()
e.divide(10, 0)
}
}
compile
and run the above example as follows
scala> scalac TryCatchFinallyEx.scala
scala> scala TryCatchFinallyEx
java.lang.ArithmeticException: / by zero
at runnerdev.ExceptionExample.divide(TryCatchFinallyEx.scala:6)
at
runnerdev.TryCatchFinallyEx$.main(TryCatchFinallyEx.scala:22)
at
runnerdev.TryCatchFinallyEx.main(TryCatchFinallyEx.scala)
()
Finaly block always executes
Rest of the code is executing