How to catch exception caused by external JARs

我怕爱的太早我们不能终老 提交于 2019-12-12 04:13:05

问题


I have a scenario like this:

I am trying to execute a command (df -h i.e command to find disk free space ) on a database server. I am trying to do so by using two JAR files i.e. jsch-0.1.51.jar and ganymed-ssh2-build210.jar .

Now when there is any worng credentails entered , It causes the below exception

com.jcraft.jsch.JSchException

But when i try to catch that exception it says:

Unreachable catch block for JSchException. This exception is never thrown from the try statement body

and the program fails how can i catch this "com.jcraft.jsch.JSchException" exception.???

Any suggestion is welcomed. Thanks in advance.

The full stacktrace is given below:

Connect fails with the following exception: com.jcraft.jsch.JSchException: java.net.UnknownHostException: Select Option

session is down com.jcraft.jsch.JSchException: session is down

at com.jcraft.jsch.Session.openChannel(Session.java:752) at net.neoremind.sshxcute.core.SSHExec.exec(SSHExec.java:164) at org.nrift.SchMaint.controller.CheckSpaceServlet.doPost(CheckSpaceServlet.java:63) at javax.servlet.http.HttpServlet.service(HttpServlet.java:647) at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)


回答1:


Well, from what I can tell the method is not declared to throw an exception so your IDE is complaining that the exception is never thrown. As a workaround you can encapsulate the method call like this:

public void openChannelHelper() throws com.jcraft.jsch.JSchException {
    // call your method here.    
}

this should allow you to do something like:

try {
    openChannelHelper();
} catch (com.jcraft.jsch.JSchException e) {
    // handle the exception here
}

Hope this helps.




回答2:


I think you have written multiple catch block but order is incorrect. You should try bellow

try {
    //your code will be here where JSchException may occur 
} catch (com.jcraft.jsch.JSchException e) {
    // write here what you want if JSchException occur
} catch (Exception e) {
    // this block for other exception
}


来源:https://stackoverflow.com/questions/23492683/how-to-catch-exception-caused-by-external-jars

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!