In Scala, exception handling is a process to handle the exception such as software or hardware exception that occurs during the execution of a program. For example, if there is an exception that occurred in the program and the exception handling code is defined then the exception handling code will be executed.
In Scala, we can use the try {...} and catch {...} block to handle exceptions.
Throw Exception
In case an error occurs, a Scala method should throw an exception instead of returning normally.
The following is an example of a throw Exception.
//execute code1
//execute code2
//execute code3
//execute code4
throw new IllegalArgumentException("Illegal Argument ...");
//The exception is generated and further statements will not be executed.
When an exception is thrown the normal sequence of execution is interrupted, and the exception is spread up the call stack until a catch clause catches it.
Try Catch Exception
If a running program is throwing an exception then it can be handled with a try-catch block but if the exception is generated from throwsException() method then the program execution flow is jumped to the catch block.
try{
throwsException();
println("this line is never executed");
} catch {
case exceptioncaught: Exception => println("exception is captured: " + exceptioncaught);
}
// method which throws exception
def throwsException() {
throw new IllegalStateException("Exception thrown");
}
Let us understand exception handling with the below example. Now save the program with the name "exceptioncatch.scala" and run it from the terminal by using the command "scala exceptioncatch.scala" (refer screenshot).
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
object exceptioncatch {
def main(args: Array[String]) {
try {
val xyz = new FileReader("data.xml")
} catch {
case ex: FileNotFoundException => {
println("Data file exception, File not found")
}
case ex: IOException => {
println("File not fund...IO Exception")
}
}
}
}
Output
Click Here To Download Code File.
Finally
The finally clause can contain code that should be executed, irrespective of an exception is thrown or not. It is appended to a try block.
try {
throwsException();
} finally {
println("Execute this code always ");
}
Let us understand exception handling with the below example. Now save the program with the name "exceptioncatch.scala" and run it from the terminal by using the command "scala exceptioncatch.scala" (refer screenshot).
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
object exceptioncatchtry {
def main(args: Array[String]) {
try {
val xyz = new FileReader("data.xml")
} catch {
case ex: FileNotFoundException => {
println("Data file exception, File not found")
}
case ex: IOException => {
println("File not fund...IO Exception")
}
} finally {
println("Execute this code always")
}
}
}
Output
Click Here To Download Code File.