开发者

how to handle nested exception in java?

I am trying to connect to mysql database. I am using try catch while establishing connection. I want that I should be able to know what exception was caught, so that, I can 开发者_如何学Cshow appropriate error message. e.g if I pass incorrect hostname, i should show Wrong hostname provided. One way to do is get class name of runtime exception class. but nested exception is being thrown like this..

There was some error while establishing connection to the databasecom.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: -- BEGIN NESTED EXCEPTION -- java.net.UnknownHostException MESSAGE: localhsost STACKTRACE: java.net.UnknownHostException: localhsost at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method) at java.net.InetAddress$1.lookupAllHostAddr(InetAddress.java:867) at java.net.InetAddress.getAddressFromNameService(InetAddress.java:1246) at java.net.InetAddress.getAllByName0(InetAddress.java:1197) at java.net.InetAddress.getAllByName(InetAddress.java:1128) at java.net.InetAddress.getAllByName(InetAddress.java:1064) at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:246) at com.mysql.jdbc.MysqlIO.(MysqlIO.java:271) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2771) at com.mysql.jdbc.Connection.(Connection.java:1555) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285) at java.sql.DriverManager.getConnection(DriverManager.java:620) at java.sql.DriverManager.getConnection(DriverManager.java:222) at accessMySQL.accessMySQL.createConnection(accessMySQL.java:24) at test.main(test.java:16) -- END NESTED EXCEPTION -- Last packet sent to the server was 1 ms ago. Problem in establishing connection.

Now I would like to know that class name UnknownHostException, so I can setup a condition like

if(e.getClass().toString() == "UnknownHostException")  
System.out.println("Exception caught while connection to database. Hostname appears to be incorrect"); 

please help !! P.s that typo in hostname is deliberately there to generate exception


Try this:

if (e.getCause() instanceof UnknownHostException) {
    // ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜