bing
Flat 10% & upto 50% off + Free additional Courses. Hurry up!

Scala Exception Handling

 

Exceptions are the events which can change the flow of control through a program. When you want to handle exceptions, you use a try{…}catch{…} block like you would in Java except that the catch block uses matching to identify and handle the exceptions.

 

Throwing Exceptions

Throwing an exception looks the same as in Java. You create an exception object and then you throw it with the throw keyword:

throw new IllegalArgumentException

 

Catching Expressions

In a single block scala permits you to try and catch exception and then it performs pattern matching by the help of case blocks.

e.g.

import java.io.FileReader

import java.io.FileNotFoundException

import java.io.IOException

object Intellipaat {

def main(args: Array[String]) {

try {

val i = new FileReader("intellipaat.txt")

} catch {

case ex: FileNotFoundException =>{

println("File not found Exception")

}

case ex: IOException => {

println("Input /Output Exception")

}

}

}

}

Output

File not found Exception

 

The finally clause:

If you want to cause some code to execute no matter how the expression terminates then you can enclose an expression with a finally clause. For example you want to close the open file even if a method exists by throwing an exception.

e.g.

import java.io.FileReader

object Intellipaat {

def main(args: Array[String]) {

val file = new FileReader("intellipaat.txt")

try {

// Use the file

} finally {

file.close() // Be sure to close the file

println(“File is closed”)

}

}

}

Output

File is closed

"0 Responses on Scala Exception Handling"

Training in Cities

Bangalore, Hyderabad, Chennai, Delhi, Kolkata, UK, London, Chicago, San Francisco, Dallas, Washington, New York, Orlando, Boston

100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.

top

Sales Offer

  • To avail this offer, enroll before 05th December 2016.
  • This offer cannot be combined with any other offer.
  • This offer is valid on selected courses only.
  • Please use coupon codes mentioned below to avail the offer
offer-june

Sign Up or Login to view the Free Scala Exception Handling.