0

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

1 Answer 1

3

Try this:

if (e.getCause() instanceof UnknownHostException) {
    // ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.