Skip to content

Instantly share code, notes, and snippets.

@Araglas88
Last active October 20, 2021 15:21
Show Gist options
  • Save Araglas88/a1594b1b849dbc94bea443d3a5cbc4aa to your computer and use it in GitHub Desktop.
Save Araglas88/a1594b1b849dbc94bea443d3a5cbc4aa to your computer and use it in GitHub Desktop.
Scala-Try-Catch-Finally.sc
In this we will see various examples of Scala Exceptional Handling.
try{
val a=5
val b=0
a/b
} catch{
case t: Throwable => println("Divide by zero error")
}
finally {
println("In finally")
}
Output:
Divide by zero error
In finally
try{
opensftpreadfile("location")
} catch{
case e: FileNotFoundException => println("Could not find file.")
case e: IOException => println("IOException during file read")
}
finally {
println("In finally")
}
try{
opensftpreadfile("location")
} catch{
case e: Throwable => println("Issue Occurred Hence Existing")
}
try{
opensftpreadfile("location")
} catch{
case e: FileNotFoundException => functionToGenerateFile()
case e: IOException => sendEmailToSupport()
case e: Throwable => print("Some Error")
}
val x: String =try{
val str = "GOOD"
str.substring(0,12)
} catch{
case e: Throwable => "Some Error"
}
finally {
println("In finally")
}
try{
val str = "GOOD"
str.charAt(20)
} catch{
case e: Throwable => println("String is short")
}
println("Reached this Step")
Output:
String is short
Reached this Step
try{
val str = "GOOD"
str.charAt(20)
} catch{
case e: Throwable => println("String is short")
throw e
}
println("Reached this Step")
Output:
String is short
java.lang.StringIndexOutOfBoundsException: String index out of range: 20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment