Mistu4u
Mistu4u

Reputation: 5416

How can I catch a specific exception

How can I catch a specific exception? For example, in Java EE project SQLException may occur. For catching purpose we write

catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   

But it can happen due to different reasons like

ORA-00001: unique constraint (SYSTEM.PK_USERID) violated

or

Listener refused the connection with the following error: ORA-12505, TNS:listener does not currently know of SID given in connect descriptor The Connection descriptor used by the client was: localhost:1521:XE .

So if I want to catch specifically which exception is happening how can I implement it in the code? A code snippet will be very much helpful!!

Upvotes: 1

Views: 2963

Answers (4)

Marko Topolnik
Marko Topolnik

Reputation: 200236

If you are talking about java.sql.SQLException, please check its Javadoc as there are a ton of subclasses of that exception that you can individually catch (and subclasses of those subclasses, as well). Plus, if you are using any frameworks, there's a chance they provide even more SQLException subclasses of their own. You can check this easily within your IDE. In Eclipse it is called the Type Hierarchy view.

Upvotes: 2

Byter
Byter

Reputation: 1132

What you have given are various messages of the SQLException. If you have to handle them differently you may have to use either if statements or switch statements for e.getMessage()

Upvotes: 0

algorowara
algorowara

Reputation: 1720

It would seem that you want to respond to exceptions differently depending on what the result of e.getMessage() is. For that purpose, I would advise a series of if statements within the catch block; you almost certainly want to catch the exception whatever it is (since uncaught exceptions are trouble), so you don't need to decide whether or not to catch based on anything other than the fact that it is an exception.

EDIT: if it is your own method throwing certain exceptions, you could subclass SQLException to signify different variations on the original class, and catch those individually.

Upvotes: 1

Markus Mikkolainen
Markus Mikkolainen

Reputation: 3497

catch, check if that is the message, if not then rethrow.

Upvotes: 1

Related Questions