SlideShare a Scribd company logo
CAND NAG ARVIND GUDISEVA 1
EXCEPTION HANDLING IN SCALA
JAVA WAY OF EXCEPTION HANDLING IN SCALA
TRY / CATCH / FINALLY
Onlyone catch blockis neededandcasesare usedto handle individual exceptions
PRESENT CODE
def oracleSample(oraConnWeb: Connection): Unit = {
logger.info(" :: Start Def :: oracleSample :: ")
try {
val oraStmt = oraConnWeb.createStatement()
var sqlSelect = """select * from emp"""
logger.info("SQL: " + sqlSelect)
val rs = oraStmt.executeQuery(sqlSelect)
while (rs.next){
println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3))
}
oraStmt.close()
}
catch {
case e: Throwable => e.printStackTrace()
}
logger.info(" :: End Def :: oracleSample :: ")
}
CAND NAG ARVIND GUDISEVA 2
MODIFIED CODE
def oracleSample(oraConnWeb: Connection): Unit = {
logger.info(" :: Start Def :: oracleSample :: ")
try {
val oraStmt = oraConnWeb.createStatement()
var sqlSelect = """select * from emp"""
logger.info("SQL: " + sqlSelect)
val rs = oraStmt.executeQuery(sqlSelect)
while (rs.next){
println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3))
}
oraStmt.close()
}
catch {
case ex: java.sql.SQLException => throw new java.sql.SQLException("SQLException: " +
ex.printStackTrace())
case ex: oracle.net.ns.NetException => throw new
oracle.net.ns.NetException(1,ex.printStackTrace().toString)
case ex: java.net.UnknownHostException => throw new
java.net.UnknownHostException("UnknownHostException: " + ex.printStackTrace())
case ex: java.sql.SQLSyntaxErrorException => throw new
java.sql.SQLSyntaxErrorException("SQLSyntaxErrorException: " + ex.printStackTrace())
case ex: Exception => throw new Exception("Exception: " + ex.printStackTrace())
}
logger.info(" :: End Def :: oracleSample :: ")
}
IMPROVISED CODE
def oracleSample(oraConnWeb: Connection): Unit = {
logger.info(" :: Start Def :: oracleSample :: ")
try {
CAND NAG ARVIND GUDISEVA 3
val oraStmt = oraConnWeb.createStatement()
var sqlSelect = """select * from emp1"""
logger.info("SQL: " + sqlSelect)
val rs = oraStmt.executeQuery(sqlSelect)
while (rs.next){
println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3))
}
oraStmt.close()
}
catch {
case ex: Exception => throw new CandAllExceptions(ex)
}
finally {
// Nothing
}
logger.info(" :: End Def :: oracleSample :: ")
}
WHAT IS THE PROBLEM?
Scala hasomittedCheckedExceptions. These exceptionsviolate SOLID –Open/ Close principle,
because we can’tthrow a newexceptioninasubclasswithoutpropagatingitaroundtoall the
existingclassesinthe hierarchy,aswell as methodscallingthose methods.
Scala’ssupportfor CheckedExceptionsisforcompatibilitywithJavacode. If we don’tintendtocall
a Scala code from Javacode,we shouldnotbe usingCheckedExceptions.
THROW NEW EXCEPTION
Throwingthe exceptionback tothe callingfunctionandhandlingthe exceptionsstackina
centralizedfashion.
PRESENT CODE
private def executeShell(shellStr: String) = {
logger.info(" :: Start Def :: executeShell :: ")
val shellCommand: String = shellStr
logger.info("Shell Command: " + shellCommand)
val sqoopProcess = Process(shellCommand).!!
logger.info("Shell Process: " + sqoopProcess)
logger.info(" :: End Def :: executeShell :: ")
}
IMPROVISED CODE
CAND NAG ARVIND GUDISEVA 4
private def executeShell(shellStr: String) = {
logger.info(" :: Start Def :: executeShell :: ")
try {
val shellCommand: String = shellStr
logger.info("Shell Command: " + shellCommand)
val stdOutput = new StringBuilder
val stdError = new StringBuilder
val processStatus: Int = shellCommand ! ProcessLogger(stdOutput append _, stdError append
_)
logger.info("Status Code: " + processStatus)
logger.info("Standard Output: " + stdOutput)
logger.info("Standard Error: " + stdError)
if(processStatus != 0){
val customCause = new RuntimeException("Non-zero Exit Code: (" + processStatus + ")")
val customException = new RuntimeException(customCause)
throw new CandCustomException(customException.getMessage, customException.getCause)
}
}
catch {
case ex: CandCustomException => throw new CandCustomException("CandCustomException: " +
ex.getMessage)
case ex: Exception => throw new CandAllExceptions(ex)
}
finally {
// Nothing
}
logger.info(" :: End Def :: executeShell :: ")
}
WHAT IS THE PROBLEM?
Shell / Processexceptionswere nevercaughtbyScalacode. Itwas handledbyJVM,whichwas
runningthe process. Enhance the code to use ProcessLoggerinsteadof Process.
PROCESS SHELL EXCEPTIONS:
Caused by: java.lang.RuntimeException: Unable to instantiate
org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient
java.io.IOException: Hive exited with status 1
USE PROCESSLOGGER INSTEAD OF PROCESS
INFO contrct.GenCustContract$: Status Code: 1
INFO contrct.GenCustContract$: Standard Output: Warning: Please set $ZOOKEEPER_HOME to the root of
your Zookeeper installation.
INFO contrct.GenCustContract$: Standard Error:
ERROR util.CandCustomException: Message: java.lang.RuntimeException: Non-zero Exit Code: (1)
CAND NAG ARVIND GUDISEVA 5
@THROWS ANNOTATION
Onlyuseful if Scalacode iscalledfromJavaProgram. Is notof muchvalue as we needto
encapsulate the callingfunctionwithatryand catch.
@throws(classOf[CandAllExceptions])
def testThrows (oraConnWeb: Connection) = {
logger.info(" :: Start Def :: testThrows :: ")
val i: Int = 1
val j: Int = 0
println("Result: " + i/j)
logger.info(" :: End Def :: testThrows :: ")
}
def callTest = {
try{
testThrows(OraDBCon.getNaiApplCon())
}
catch {
case ex: Exception => throw new CandAllExceptions(ex)
}
}
CUSTOM EXCEPTIONS
Everyexceptionhasamessage andcause. CustomExceptionare extendedfromRuntimeException.
Hence,message andcause needstobe populatedwhengeneratingaCustomException.
package com.cisco.cand.util
import grizzled.slf4j.Logger
class CandCustomException(message: String = null, cause: Throwable = null) extends
RuntimeException(CandCustomException.customMessage(message, cause), cause)
/**
* Created by Nag Arvind Gudiseva on 08-July-2016.
*/
object CandCustomException {
val logger = Logger(classOf[CandCustomException])
logger.info(" :: Start Object :: CandCustomException :: ")
def customMessage(message: String, cause: Throwable) = {
if (message != null) {
logger.error("Message: " + message)
message
}
else if (cause != null){
logger.error("Cause: " + cause.toString())
cause.toString()
}
else
CAND NAG ARVIND GUDISEVA 6
null
}
logger.info(" :: End Object :: CandCustomException :: ")
}
EXCEPTIONS STACK / CENTRALIZED HANDLING OF ALL EXCEPTIONS
The purpose of thisCentralizedExceptionhandlingistokeepthe catchclause of code cleanand
simple. Exceptiontype isrecognizedasperthe exceptioninstance andthe stacktrace isprinted.
package com.cisco.cand.util
import grizzled.slf4j.Logger
/**
* Created by Nag Arvind Gudiseva on 11-July-2016.
*/
object CandAllExceptions {
val logger = Logger(classOf[CandAllExceptions])
logger.info(" :: Start Object :: CandAllExceptions :: ")
class CandAllExceptions(exception: Exception) extends Exception {
if (exception.isInstanceOf[java.sql.SQLSyntaxErrorException]){
throw new java.sql.SQLSyntaxErrorException("SQLSyntaxErrorException: " +
exception.printStackTrace)
}
else if(exception.isInstanceOf[java.sql.SQLException]){
throw new java.sql.SQLException("SQLException: " + exception.printStackTrace)
}
else if (exception.isInstanceOf[oracle.net.ns.NetException]){
throw new oracle.net.ns.NetException(1,exception.printStackTrace.toString)
}
else if (exception.isInstanceOf[java.net.UnknownHostException]){
throw new java.net.UnknownHostException("UnknownHostException: " +
exception.printStackTrace)
}
else if (exception.isInstanceOf[org.apache.thrift.transport.TTransportException]){
throw new org.apache.thrift.transport.TTransportException("ThriftTransportException: " +
exception.printStackTrace)
}
else if (exception.isInstanceOf[java.lang.NullPointerException]){
throw new java.lang.NullPointerException("NullPointerException: " +
exception.printStackTrace)
}
else if (exception.isInstanceOf[java.io.IOException]){
throw new java.io.IOException("IOException: " + exception.printStackTrace)
}
else if (exception.isInstanceOf[java.lang.RuntimeException]){
throw new java.lang.RuntimeException("RuntimeException: " + exception.printStackTrace)
}
else if (exception.isInstanceOf[java.lang.ArithmeticException]){
throw new java.lang.ArithmeticException("ArithmeticException: " +
exception.printStackTrace)
}
else{
throw new Exception("Exception: " + exception.printStackTrace)
}
}
logger.info(" :: End Object :: CandAllExceptions :: ")
}
CAND NAG ARVIND GUDISEVA 7
FINAL NOTE
Enhancedexceptionshandlingcode isinjectedtothe existingScalacode. There isno change inthe
existingfunctionality.

More Related Content

What's hot

Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
ikikko
 
Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Kiyotaka Oku
 
Java
JavaJava
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Anton Arhipov
 
The Ring programming language version 1.6 book - Part 41 of 189
The Ring programming language version 1.6 book - Part 41 of 189The Ring programming language version 1.6 book - Part 41 of 189
The Ring programming language version 1.6 book - Part 41 of 189
Mahmoud Samir Fayed
 
Алексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereАлексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhere
Sergey Platonov
 
Java Performance Puzzlers
Java Performance PuzzlersJava Performance Puzzlers
Java Performance Puzzlers
Doug Hawkins
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with Javassist
Anton Arhipov
 
The Ring programming language version 1.10 book - Part 94 of 212
The Ring programming language version 1.10 book - Part 94 of 212The Ring programming language version 1.10 book - Part 94 of 212
The Ring programming language version 1.10 book - Part 94 of 212
Mahmoud Samir Fayed
 
RxJava и Android. Плюсы, минусы, подводные камни
RxJava и Android. Плюсы, минусы, подводные камниRxJava и Android. Плюсы, минусы, подводные камни
RxJava и Android. Плюсы, минусы, подводные камни
Stfalcon Meetups
 
Thread dumps
Thread dumpsThread dumps
Thread dumps
Ajit Bhingarkar
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...julien.ponge
 
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅
재춘 노
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With Spock
IT Weekend
 
Fia fabila
Fia fabilaFia fabila
Fia fabila
fiafabila
 
201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian
KhairunnisaPekanbaru
 
Testing (eng)
Testing (eng)Testing (eng)
Testing (eng)
Derrick Chao
 
JVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's TricksJVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's Tricks
Doug Hawkins
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with Javassist
Anton Arhipov
 

What's hot (20)

Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
 
Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介
 
Java
JavaJava
Java
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
 
The Ring programming language version 1.6 book - Part 41 of 189
The Ring programming language version 1.6 book - Part 41 of 189The Ring programming language version 1.6 book - Part 41 of 189
The Ring programming language version 1.6 book - Part 41 of 189
 
Алексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereАлексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhere
 
Java Performance Puzzlers
Java Performance PuzzlersJava Performance Puzzlers
Java Performance Puzzlers
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with Javassist
 
The Ring programming language version 1.10 book - Part 94 of 212
The Ring programming language version 1.10 book - Part 94 of 212The Ring programming language version 1.10 book - Part 94 of 212
The Ring programming language version 1.10 book - Part 94 of 212
 
RxJava и Android. Плюсы, минусы, подводные камни
RxJava и Android. Плюсы, минусы, подводные камниRxJava и Android. Плюсы, минусы, подводные камни
RxJava и Android. Плюсы, минусы, подводные камни
 
Thread dumps
Thread dumpsThread dumps
Thread dumps
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With Spock
 
Fia fabila
Fia fabilaFia fabila
Fia fabila
 
201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian
 
Testing (eng)
Testing (eng)Testing (eng)
Testing (eng)
 
JVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's TricksJVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's Tricks
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with Javassist
 

Viewers also liked

Scala collection
Scala collectionScala collection
Scala collection
Knoldus Inc.
 
Concurrent and Distributed Applications with Akka, Java and Scala
Concurrent and Distributed Applications with Akka, Java and ScalaConcurrent and Distributed Applications with Akka, Java and Scala
Concurrent and Distributed Applications with Akka, Java and Scala
Fernando Rodriguez
 
Introduction to Option monad in Scala
Introduction to Option monad in ScalaIntroduction to Option monad in Scala
Introduction to Option monad in Scala
Jan Krag
 
Java to Scala: Why & How
Java to Scala: Why & HowJava to Scala: Why & How
Java to Scala: Why & How
Graham Tackley
 
Origami, a monadic fold library for Scala
Origami, a monadic fold library for ScalaOrigami, a monadic fold library for Scala
Origami, a monadic fold library for Scala
Eric Torreborre
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
Lemi Orhan Ergin
 
Psicologia del color
Psicologia del colorPsicologia del color
Psicologia del color
Nicolas Pino
 
αγογ ευρυαλη μπασκετ
αγογ ευρυαλη μπασκεταγογ ευρυαλη μπασκετ
αγογ ευρυαλη μπασκετsteward56
 
Jx webinar csr-materiality-brand-v1-condensed
Jx webinar csr-materiality-brand-v1-condensedJx webinar csr-materiality-brand-v1-condensed
Jx webinar csr-materiality-brand-v1-condensed
Adam Garfunkel
 
Tugas persentasi pak kuswandi
Tugas persentasi pak kuswandiTugas persentasi pak kuswandi
Tugas persentasi pak kuswandiDyan Hatining
 
Gustavo grammar book
Gustavo grammar bookGustavo grammar book
Gustavo grammar book
graham10baseball
 
Clown fish habitat
Clown fish habitatClown fish habitat
Clown fish habitat
Megan18
 
Pheonix 360 (2)
Pheonix 360 (2)Pheonix 360 (2)
Pheonix 360 (2)
SpencerGreening
 
Газовый напольный котел Bosch ZBS 30/210 S solar
Газовый напольный котел Bosch ZBS 30/210 S solarГазовый напольный котел Bosch ZBS 30/210 S solar
Газовый напольный котел Bosch ZBS 30/210 S solar
Al Maks
 
icabihal sayi 1
icabihal sayi 1icabihal sayi 1
icabihal sayi 1
kolormatik
 
Time management
Time managementTime management
Time management
nctcmedia12
 
13. sah in mexico
13. sah in mexico13. sah in mexico
13. sah in mexico
Erwin Chiquete, MD, PhD
 
Ruta de aprendizaje semana 3
Ruta de aprendizaje semana 3Ruta de aprendizaje semana 3
Ruta de aprendizaje semana 3
Kattia Rodriguez
 
Unauthorizaed residents
Unauthorizaed residentsUnauthorizaed residents
Unauthorizaed residentsislaysn
 

Viewers also liked (20)

Scala collection
Scala collectionScala collection
Scala collection
 
Concurrent and Distributed Applications with Akka, Java and Scala
Concurrent and Distributed Applications with Akka, Java and ScalaConcurrent and Distributed Applications with Akka, Java and Scala
Concurrent and Distributed Applications with Akka, Java and Scala
 
Introduction to Option monad in Scala
Introduction to Option monad in ScalaIntroduction to Option monad in Scala
Introduction to Option monad in Scala
 
Java to Scala: Why & How
Java to Scala: Why & HowJava to Scala: Why & How
Java to Scala: Why & How
 
Origami, a monadic fold library for Scala
Origami, a monadic fold library for ScalaOrigami, a monadic fold library for Scala
Origami, a monadic fold library for Scala
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
 
Psicologia del color
Psicologia del colorPsicologia del color
Psicologia del color
 
αγογ ευρυαλη μπασκετ
αγογ ευρυαλη μπασκεταγογ ευρυαλη μπασκετ
αγογ ευρυαλη μπασκετ
 
Jx webinar csr-materiality-brand-v1-condensed
Jx webinar csr-materiality-brand-v1-condensedJx webinar csr-materiality-brand-v1-condensed
Jx webinar csr-materiality-brand-v1-condensed
 
Tugas persentasi pak kuswandi
Tugas persentasi pak kuswandiTugas persentasi pak kuswandi
Tugas persentasi pak kuswandi
 
Gustavo grammar book
Gustavo grammar bookGustavo grammar book
Gustavo grammar book
 
Clown fish habitat
Clown fish habitatClown fish habitat
Clown fish habitat
 
Pheonix 360 (2)
Pheonix 360 (2)Pheonix 360 (2)
Pheonix 360 (2)
 
Jurnal kpt6044
Jurnal kpt6044Jurnal kpt6044
Jurnal kpt6044
 
Газовый напольный котел Bosch ZBS 30/210 S solar
Газовый напольный котел Bosch ZBS 30/210 S solarГазовый напольный котел Bosch ZBS 30/210 S solar
Газовый напольный котел Bosch ZBS 30/210 S solar
 
icabihal sayi 1
icabihal sayi 1icabihal sayi 1
icabihal sayi 1
 
Time management
Time managementTime management
Time management
 
13. sah in mexico
13. sah in mexico13. sah in mexico
13. sah in mexico
 
Ruta de aprendizaje semana 3
Ruta de aprendizaje semana 3Ruta de aprendizaje semana 3
Ruta de aprendizaje semana 3
 
Unauthorizaed residents
Unauthorizaed residentsUnauthorizaed residents
Unauthorizaed residents
 

Similar to Exception Handling in Scala

Unit 5 notes.pdf
Unit 5 notes.pdfUnit 5 notes.pdf
Unit 5 notes.pdf
Revathiparamanathan
 
Hello scala
Hello scalaHello scala
Hello scala
Jinliang Ou
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
Stuart Roebuck
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
Michael Stal
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - iiRavindra Rathore
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
Ecommerce Solution Provider SysIQ
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
Ara Pehlivanian
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
rohitgudasi18
 
Introduction aux Macros
Introduction aux MacrosIntroduction aux Macros
Introduction aux Macrosunivalence
 
TDC2018SP | Trilha Go - Processando analise genetica em background com Go
TDC2018SP | Trilha Go - Processando analise genetica em background com GoTDC2018SP | Trilha Go - Processando analise genetica em background com Go
TDC2018SP | Trilha Go - Processando analise genetica em background com Go
tdc-globalcode
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
Piotr Pelczar
 
Spock: A Highly Logical Way To Test
Spock: A Highly Logical Way To TestSpock: A Highly Logical Way To Test
Spock: A Highly Logical Way To Test
Howard Lewis Ship
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
Stuart Roebuck
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in JavaPrasad Sawant
 
Learning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security APILearning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security API
caswenson
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
Pavlo Baron
 
Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016
Holden Karau
 
Pattern Matching in Java 14
Pattern Matching in Java 14Pattern Matching in Java 14
Pattern Matching in Java 14
GlobalLogic Ukraine
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 

Similar to Exception Handling in Scala (20)

Unit 5 notes.pdf
Unit 5 notes.pdfUnit 5 notes.pdf
Unit 5 notes.pdf
 
Hello scala
Hello scalaHello scala
Hello scala
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - ii
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
 
Introduction aux Macros
Introduction aux MacrosIntroduction aux Macros
Introduction aux Macros
 
TDC2018SP | Trilha Go - Processando analise genetica em background com Go
TDC2018SP | Trilha Go - Processando analise genetica em background com GoTDC2018SP | Trilha Go - Processando analise genetica em background com Go
TDC2018SP | Trilha Go - Processando analise genetica em background com Go
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Spock: A Highly Logical Way To Test
Spock: A Highly Logical Way To TestSpock: A Highly Logical Way To Test
Spock: A Highly Logical Way To Test
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Learning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security APILearning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security API
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016
 
Pattern Matching in Java 14
Pattern Matching in Java 14Pattern Matching in Java 14
Pattern Matching in Java 14
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 

More from Nag Arvind Gudiseva

Elasticsearch security
Elasticsearch securityElasticsearch security
Elasticsearch security
Nag Arvind Gudiseva
 
Elasticsearch Security Strategy
Elasticsearch Security StrategyElasticsearch Security Strategy
Elasticsearch Security Strategy
Nag Arvind Gudiseva
 
Git as version control for Analytics project
Git as version control for Analytics projectGit as version control for Analytics project
Git as version control for Analytics project
Nag Arvind Gudiseva
 
Hive performance optimizations
Hive performance optimizationsHive performance optimizations
Hive performance optimizations
Nag Arvind Gudiseva
 
Creating executable JAR from Eclipse IDE
Creating executable JAR from Eclipse IDECreating executable JAR from Eclipse IDE
Creating executable JAR from Eclipse IDE
Nag Arvind Gudiseva
 
Adding Idea IntelliJ projects to Subversion Version Control
Adding Idea IntelliJ projects to Subversion Version ControlAdding Idea IntelliJ projects to Subversion Version Control
Adding Idea IntelliJ projects to Subversion Version Control
Nag Arvind Gudiseva
 
Apache Drill with Oracle, Hive and HBase
Apache Drill with Oracle, Hive and HBaseApache Drill with Oracle, Hive and HBase
Apache Drill with Oracle, Hive and HBase
Nag Arvind Gudiseva
 
ElasticSearch Hands On
ElasticSearch Hands OnElasticSearch Hands On
ElasticSearch Hands On
Nag Arvind Gudiseva
 
Hadoop 2.0 cluster setup on ubuntu 14.04 (64 bit)
Hadoop 2.0 cluster setup on ubuntu 14.04 (64 bit)Hadoop 2.0 cluster setup on ubuntu 14.04 (64 bit)
Hadoop 2.0 cluster setup on ubuntu 14.04 (64 bit)
Nag Arvind Gudiseva
 
Order Review Solution Application (Version 2.0)
Order Review Solution Application (Version 2.0)Order Review Solution Application (Version 2.0)
Order Review Solution Application (Version 2.0)
Nag Arvind Gudiseva
 
MSC Temporary Passwords reset tool
MSC Temporary Passwords reset toolMSC Temporary Passwords reset tool
MSC Temporary Passwords reset tool
Nag Arvind Gudiseva
 
Store Support Operations - Training on MSC Application
Store Support Operations - Training on MSC ApplicationStore Support Operations - Training on MSC Application
Store Support Operations - Training on MSC Application
Nag Arvind Gudiseva
 
Store Support Operations - Training on MSC Application
Store Support Operations - Training on MSC ApplicationStore Support Operations - Training on MSC Application
Store Support Operations - Training on MSC Application
Nag Arvind Gudiseva
 

More from Nag Arvind Gudiseva (13)

Elasticsearch security
Elasticsearch securityElasticsearch security
Elasticsearch security
 
Elasticsearch Security Strategy
Elasticsearch Security StrategyElasticsearch Security Strategy
Elasticsearch Security Strategy
 
Git as version control for Analytics project
Git as version control for Analytics projectGit as version control for Analytics project
Git as version control for Analytics project
 
Hive performance optimizations
Hive performance optimizationsHive performance optimizations
Hive performance optimizations
 
Creating executable JAR from Eclipse IDE
Creating executable JAR from Eclipse IDECreating executable JAR from Eclipse IDE
Creating executable JAR from Eclipse IDE
 
Adding Idea IntelliJ projects to Subversion Version Control
Adding Idea IntelliJ projects to Subversion Version ControlAdding Idea IntelliJ projects to Subversion Version Control
Adding Idea IntelliJ projects to Subversion Version Control
 
Apache Drill with Oracle, Hive and HBase
Apache Drill with Oracle, Hive and HBaseApache Drill with Oracle, Hive and HBase
Apache Drill with Oracle, Hive and HBase
 
ElasticSearch Hands On
ElasticSearch Hands OnElasticSearch Hands On
ElasticSearch Hands On
 
Hadoop 2.0 cluster setup on ubuntu 14.04 (64 bit)
Hadoop 2.0 cluster setup on ubuntu 14.04 (64 bit)Hadoop 2.0 cluster setup on ubuntu 14.04 (64 bit)
Hadoop 2.0 cluster setup on ubuntu 14.04 (64 bit)
 
Order Review Solution Application (Version 2.0)
Order Review Solution Application (Version 2.0)Order Review Solution Application (Version 2.0)
Order Review Solution Application (Version 2.0)
 
MSC Temporary Passwords reset tool
MSC Temporary Passwords reset toolMSC Temporary Passwords reset tool
MSC Temporary Passwords reset tool
 
Store Support Operations - Training on MSC Application
Store Support Operations - Training on MSC ApplicationStore Support Operations - Training on MSC Application
Store Support Operations - Training on MSC Application
 
Store Support Operations - Training on MSC Application
Store Support Operations - Training on MSC ApplicationStore Support Operations - Training on MSC Application
Store Support Operations - Training on MSC Application
 

Recently uploaded

Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 

Recently uploaded (20)

Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 

Exception Handling in Scala

  • 1. CAND NAG ARVIND GUDISEVA 1 EXCEPTION HANDLING IN SCALA JAVA WAY OF EXCEPTION HANDLING IN SCALA TRY / CATCH / FINALLY Onlyone catch blockis neededandcasesare usedto handle individual exceptions PRESENT CODE def oracleSample(oraConnWeb: Connection): Unit = { logger.info(" :: Start Def :: oracleSample :: ") try { val oraStmt = oraConnWeb.createStatement() var sqlSelect = """select * from emp""" logger.info("SQL: " + sqlSelect) val rs = oraStmt.executeQuery(sqlSelect) while (rs.next){ println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3)) } oraStmt.close() } catch { case e: Throwable => e.printStackTrace() } logger.info(" :: End Def :: oracleSample :: ") }
  • 2. CAND NAG ARVIND GUDISEVA 2 MODIFIED CODE def oracleSample(oraConnWeb: Connection): Unit = { logger.info(" :: Start Def :: oracleSample :: ") try { val oraStmt = oraConnWeb.createStatement() var sqlSelect = """select * from emp""" logger.info("SQL: " + sqlSelect) val rs = oraStmt.executeQuery(sqlSelect) while (rs.next){ println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3)) } oraStmt.close() } catch { case ex: java.sql.SQLException => throw new java.sql.SQLException("SQLException: " + ex.printStackTrace()) case ex: oracle.net.ns.NetException => throw new oracle.net.ns.NetException(1,ex.printStackTrace().toString) case ex: java.net.UnknownHostException => throw new java.net.UnknownHostException("UnknownHostException: " + ex.printStackTrace()) case ex: java.sql.SQLSyntaxErrorException => throw new java.sql.SQLSyntaxErrorException("SQLSyntaxErrorException: " + ex.printStackTrace()) case ex: Exception => throw new Exception("Exception: " + ex.printStackTrace()) } logger.info(" :: End Def :: oracleSample :: ") } IMPROVISED CODE def oracleSample(oraConnWeb: Connection): Unit = { logger.info(" :: Start Def :: oracleSample :: ") try {
  • 3. CAND NAG ARVIND GUDISEVA 3 val oraStmt = oraConnWeb.createStatement() var sqlSelect = """select * from emp1""" logger.info("SQL: " + sqlSelect) val rs = oraStmt.executeQuery(sqlSelect) while (rs.next){ println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3)) } oraStmt.close() } catch { case ex: Exception => throw new CandAllExceptions(ex) } finally { // Nothing } logger.info(" :: End Def :: oracleSample :: ") } WHAT IS THE PROBLEM? Scala hasomittedCheckedExceptions. These exceptionsviolate SOLID –Open/ Close principle, because we can’tthrow a newexceptioninasubclasswithoutpropagatingitaroundtoall the existingclassesinthe hierarchy,aswell as methodscallingthose methods. Scala’ssupportfor CheckedExceptionsisforcompatibilitywithJavacode. If we don’tintendtocall a Scala code from Javacode,we shouldnotbe usingCheckedExceptions. THROW NEW EXCEPTION Throwingthe exceptionback tothe callingfunctionandhandlingthe exceptionsstackina centralizedfashion. PRESENT CODE private def executeShell(shellStr: String) = { logger.info(" :: Start Def :: executeShell :: ") val shellCommand: String = shellStr logger.info("Shell Command: " + shellCommand) val sqoopProcess = Process(shellCommand).!! logger.info("Shell Process: " + sqoopProcess) logger.info(" :: End Def :: executeShell :: ") } IMPROVISED CODE
  • 4. CAND NAG ARVIND GUDISEVA 4 private def executeShell(shellStr: String) = { logger.info(" :: Start Def :: executeShell :: ") try { val shellCommand: String = shellStr logger.info("Shell Command: " + shellCommand) val stdOutput = new StringBuilder val stdError = new StringBuilder val processStatus: Int = shellCommand ! ProcessLogger(stdOutput append _, stdError append _) logger.info("Status Code: " + processStatus) logger.info("Standard Output: " + stdOutput) logger.info("Standard Error: " + stdError) if(processStatus != 0){ val customCause = new RuntimeException("Non-zero Exit Code: (" + processStatus + ")") val customException = new RuntimeException(customCause) throw new CandCustomException(customException.getMessage, customException.getCause) } } catch { case ex: CandCustomException => throw new CandCustomException("CandCustomException: " + ex.getMessage) case ex: Exception => throw new CandAllExceptions(ex) } finally { // Nothing } logger.info(" :: End Def :: executeShell :: ") } WHAT IS THE PROBLEM? Shell / Processexceptionswere nevercaughtbyScalacode. Itwas handledbyJVM,whichwas runningthe process. Enhance the code to use ProcessLoggerinsteadof Process. PROCESS SHELL EXCEPTIONS: Caused by: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient java.io.IOException: Hive exited with status 1 USE PROCESSLOGGER INSTEAD OF PROCESS INFO contrct.GenCustContract$: Status Code: 1 INFO contrct.GenCustContract$: Standard Output: Warning: Please set $ZOOKEEPER_HOME to the root of your Zookeeper installation. INFO contrct.GenCustContract$: Standard Error: ERROR util.CandCustomException: Message: java.lang.RuntimeException: Non-zero Exit Code: (1)
  • 5. CAND NAG ARVIND GUDISEVA 5 @THROWS ANNOTATION Onlyuseful if Scalacode iscalledfromJavaProgram. Is notof muchvalue as we needto encapsulate the callingfunctionwithatryand catch. @throws(classOf[CandAllExceptions]) def testThrows (oraConnWeb: Connection) = { logger.info(" :: Start Def :: testThrows :: ") val i: Int = 1 val j: Int = 0 println("Result: " + i/j) logger.info(" :: End Def :: testThrows :: ") } def callTest = { try{ testThrows(OraDBCon.getNaiApplCon()) } catch { case ex: Exception => throw new CandAllExceptions(ex) } } CUSTOM EXCEPTIONS Everyexceptionhasamessage andcause. CustomExceptionare extendedfromRuntimeException. Hence,message andcause needstobe populatedwhengeneratingaCustomException. package com.cisco.cand.util import grizzled.slf4j.Logger class CandCustomException(message: String = null, cause: Throwable = null) extends RuntimeException(CandCustomException.customMessage(message, cause), cause) /** * Created by Nag Arvind Gudiseva on 08-July-2016. */ object CandCustomException { val logger = Logger(classOf[CandCustomException]) logger.info(" :: Start Object :: CandCustomException :: ") def customMessage(message: String, cause: Throwable) = { if (message != null) { logger.error("Message: " + message) message } else if (cause != null){ logger.error("Cause: " + cause.toString()) cause.toString() } else
  • 6. CAND NAG ARVIND GUDISEVA 6 null } logger.info(" :: End Object :: CandCustomException :: ") } EXCEPTIONS STACK / CENTRALIZED HANDLING OF ALL EXCEPTIONS The purpose of thisCentralizedExceptionhandlingistokeepthe catchclause of code cleanand simple. Exceptiontype isrecognizedasperthe exceptioninstance andthe stacktrace isprinted. package com.cisco.cand.util import grizzled.slf4j.Logger /** * Created by Nag Arvind Gudiseva on 11-July-2016. */ object CandAllExceptions { val logger = Logger(classOf[CandAllExceptions]) logger.info(" :: Start Object :: CandAllExceptions :: ") class CandAllExceptions(exception: Exception) extends Exception { if (exception.isInstanceOf[java.sql.SQLSyntaxErrorException]){ throw new java.sql.SQLSyntaxErrorException("SQLSyntaxErrorException: " + exception.printStackTrace) } else if(exception.isInstanceOf[java.sql.SQLException]){ throw new java.sql.SQLException("SQLException: " + exception.printStackTrace) } else if (exception.isInstanceOf[oracle.net.ns.NetException]){ throw new oracle.net.ns.NetException(1,exception.printStackTrace.toString) } else if (exception.isInstanceOf[java.net.UnknownHostException]){ throw new java.net.UnknownHostException("UnknownHostException: " + exception.printStackTrace) } else if (exception.isInstanceOf[org.apache.thrift.transport.TTransportException]){ throw new org.apache.thrift.transport.TTransportException("ThriftTransportException: " + exception.printStackTrace) } else if (exception.isInstanceOf[java.lang.NullPointerException]){ throw new java.lang.NullPointerException("NullPointerException: " + exception.printStackTrace) } else if (exception.isInstanceOf[java.io.IOException]){ throw new java.io.IOException("IOException: " + exception.printStackTrace) } else if (exception.isInstanceOf[java.lang.RuntimeException]){ throw new java.lang.RuntimeException("RuntimeException: " + exception.printStackTrace) } else if (exception.isInstanceOf[java.lang.ArithmeticException]){ throw new java.lang.ArithmeticException("ArithmeticException: " + exception.printStackTrace) } else{ throw new Exception("Exception: " + exception.printStackTrace) } } logger.info(" :: End Object :: CandAllExceptions :: ") }
  • 7. CAND NAG ARVIND GUDISEVA 7 FINAL NOTE Enhancedexceptionshandlingcode isinjectedtothe existingScalacode. There isno change inthe existingfunctionality.