Scala Exception handling - Scala

What is Scala - Exception Handling?

Scala's exceptions work like exceptions in many other languages similar to Java Programming language. Instead of returning a value in the normal way, a method can exit by throwing an exception. However, Scala will not have checked exceptions.

When we want to handle these exceptions, we can use a try{...}catch{...} block like we would be using in Java except that the catch block uses matching to identify and handle the exceptions.

Throwing Exceptions

Throwing an exception looks the same like as in Java. We will be creating an exception object and then we throw it with the throw keyword as displayed below.

Catching Exceptions

Scala lets the user to use try/catch any exception in a single block and also perform pattern matching against it using case blocks. Try the below example program in order to handle exception.

Example

We need to save the above program in Demo.scala. The below displayed commands are used to compile and run this program.

Command

Output

The behavior of this try-catch expression is similar to that as in other languages with exceptions. First the body is executed, and if it throws an exception, each catch clause is tried in turn.

The finally Clause

We can wrap an expression with a finally clause if we are willing to cause some code to run, no matter how the expression terminates. Try the below sample program.

Example

We need to save the above program inDemo.scala. The below displayed commands are used to compile and run this program.

Command

Output

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Scala Topics