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.
Ad

More Related Content

What's hot (20)

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
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
Anton 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
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
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
 
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
 
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
Anton 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
 
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
 
201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian
KhairunnisaPekanbaru
 
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
 

Viewers also liked (20)

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 kuswandi
Dyan 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 residents
islaysn
 
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 kuswandi
Dyan Hatining
 
Clown fish habitat
Clown fish habitatClown fish habitat
Clown fish habitat
Megan18
 
Газовый напольный котел 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
 
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 residents
islaysn
 
Ad

Similar to Exception Handling in Scala (20)

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 - ii
Ravindra 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 Macros
univalence
 
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 Java
Prasad 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
 
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 - ii
Ravindra Rathore
 
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 Macros
univalence
 
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 Java
Prasad 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
 
(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
 
Ad

More from Nag Arvind Gudiseva (13)

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
 
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
 
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
 
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
 

Recently uploaded (20)

The Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI IntegrationThe Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI Integration
Re-solution Data Ltd
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Vibe Coding_ Develop a web application using AI (1).pdf
Vibe Coding_ Develop a web application using AI (1).pdfVibe Coding_ Develop a web application using AI (1).pdf
Vibe Coding_ Develop a web application using AI (1).pdf
Baiju Muthukadan
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptxWebinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
MSP360
 
Play It Safe: Manage Security Risks - Google Certificate
Play It Safe: Manage Security Risks - Google CertificatePlay It Safe: Manage Security Risks - Google Certificate
Play It Safe: Manage Security Risks - Google Certificate
VICTOR MAESTRE RAMIREZ
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
Connect and Protect: Networks and Network Security
Connect and Protect: Networks and Network SecurityConnect and Protect: Networks and Network Security
Connect and Protect: Networks and Network Security
VICTOR MAESTRE RAMIREZ
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
TrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token ListingTrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token Listing
Trs Labs
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and MLGyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
Gyrus AI
 
The Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI IntegrationThe Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI Integration
Re-solution Data Ltd
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Vibe Coding_ Develop a web application using AI (1).pdf
Vibe Coding_ Develop a web application using AI (1).pdfVibe Coding_ Develop a web application using AI (1).pdf
Vibe Coding_ Develop a web application using AI (1).pdf
Baiju Muthukadan
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptxWebinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
MSP360
 
Play It Safe: Manage Security Risks - Google Certificate
Play It Safe: Manage Security Risks - Google CertificatePlay It Safe: Manage Security Risks - Google Certificate
Play It Safe: Manage Security Risks - Google Certificate
VICTOR MAESTRE RAMIREZ
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
Connect and Protect: Networks and Network Security
Connect and Protect: Networks and Network SecurityConnect and Protect: Networks and Network Security
Connect and Protect: Networks and Network Security
VICTOR MAESTRE RAMIREZ
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
TrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token ListingTrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token Listing
Trs Labs
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and MLGyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
Gyrus AI
 

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.