简体   繁体   中英

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

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.

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.

catch,检查是否是消息,如果没有那么重新抛出。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM