...

Cloud Computing - SCALA

Back to Course

Lesson Description


Lession - #696 SCALA EXCEPTION HANDLING


Exception Handling

Scala's exceptions work like exceptions in numerous different languages like Java. Rather than returning a value in the normal manner, a method can end by throwing an exemption. Be that as it may, Scala doesn't really have actually taken a look at exceptions.

Whenever you need to handle with special cases, you utilize a try{...}catch{...} block like you would in Java aside from that the catch block utilizes matching to recognize and handle with the exceptions.

Throwing Exceptions
Throwing an exemption looks equivalent to in Java. You make a special case object and afterward you throw it with the throw keyword as follows.

throw new IllegalArgumentException
Catching Exceptions
Scala permits you to try/catch any exception in a single block and afterward perform pattern matching against it utilizing case blocks. try the following model program to handle with special case.

Model
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException

object Demo {
   def main(args: Array[String]>
{ try { val f = new FileReader("input.txt">
} catch { case ex: FileNotFoundException =>{ println("Missing document special case">
} case ex: IOException => { println("IO Exception">
} } } }



Save the above program in Demo.scala. The following commands are utilized to compile and execute this program.
Command

\>scalac Demo.scala
\>scala Demo


Yield

Missing record exemption


The way of behaving of this try catch expression is equivalent to in different language with exceptions. The body is executed, and if it throwes an exemption, each catch provision is tryed turn.

The finally Clause
You can wrap an expression with an finally statement if you have any desire to make some code execute regardless of how the expression ends. try the following project.

Model
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException

object Demo {
   def main(args: Array[String]>
{ try { val f = new FileReader("input.txt">
} catch { case ex: FileNotFoundException => { println("Missing record exemption">
} case ex: IOException => { println("IO Exception">
} } at long last { println("Exiting finally...">
} } }



Save the above program in Demo.scala. The following commands are utilized to compile and execute this program.
command

\>scalac Demo.scala
\>scala Demo

Yield

Missing document exemption
Leaving finally...