File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes How to get exact exception type Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to get exact exception type" Watch "How to get exact exception type" New topic

How to get exact exception type

Shantanu Deshmukh

Joined: Jul 28, 2011
Posts: 23


I am trying to connect to mysql database using JDBC. I have applied exception handling. However simply printing exception object is amateur. I want to know exact reason of exception.
For example, if I give wrong hostname it should give me exception that Hostname was incorrect.
How to go about it ?

There are no failures, only experiences
Rob Spoor

Joined: Oct 27, 2005
Posts: 20269

SQLException has method getErrorCode() that returns a vendor-specific error code that indicates what exactly went wrong. Combined with getMessage() and possibly getSQLState() that's all the info you have.

How To Ask Questions How To Answer Questions
Shantanu Deshmukh

Joined: Jul 28, 2011
Posts: 23

So this is the function I am going to use.

How can I use SQLException here?
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10815

You have the catch block empty. Very bad idea.
Either have multiple catch blocks or use

Edit: Corrected typo. Thanks Seetharaman and Campbell

[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Don't swallow an exception. log the exception message for debugging as in below:

@maneesh:you have beaten me nicely! there is a typo in your casting idiom
Darryl Burke

Joined: May 03, 2008
Posts: 5115

Also see

luck, db
There are no new questions, but there may be new answers.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46323
Maneesh Godbole wrote:. . . or use
. . .
And check the position of all ) carefully before proceeding.
I agree. Here's the link:
subject: How to get exact exception type
It's not a secret anymore!