Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Catching a SQLException

 
Grant Morris
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a question about catching a SQLException in an object of type Exception. I'm catching all my exceptions in objects of type Exception; however, I want to check to see if the thrown exception is a SQLException. If the thrown exception is a SQLException, I want to check the sql error code and return an appropriate message. If the thrown exception is not a SQLException, just exit.

Thanks for the help.
 
Sakti Singh
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if more than one exception raised by a piece of code you can specify more than one catch clauses , where each catch clause will catch a diff type of exception.
for eg.
try {
// your code
}
catch(SQLException se) { //-------1
se.printStackTrace();
}
catch(Exception e) { //----------2
e.printStackTrace();
}
Note: Exception class is super class of all other exceptios..hence should be caught last(last catch block)....
if u change the order of catch blocks to 2--1 , then 1 block will never be executed as 2 is capable of catching all the exceptions
Hope this will solve ur problem
thanks
Sakti
 
Bosun Bello
Ranch Hand
Posts: 1510
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can also check if your exception object is an instance of SQLException.
ie Catch(Exception e)
if (e instanceof SQLException)
do whatever...

Bosun
 
Yogen Vadnere
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not like that bosun,
try {
// your code
}
catch(SQLException se) { //-------1
//this block will get execute only if ur code throws SQL exception
//there is no need to use instanceof operator
//just write ur SQL exception related code here..
}
catch(Exception e) { //----------2
e.printStackTrace();
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic