【问题标题】:exception CertificateException is never thrown in body of corresponding try statement在相应的 try 语句的主体中永远不会抛出异常 CertificateException
【发布时间】:2014-11-30 08:55:49
【问题描述】:

我正在尝试使用 java 读取 URL

try{
    HttpURLConnection c = (HttpURLConnection) new URL(args[0]).openConnection();
    c.setRequestMethod("GET");
    c.setRequestProperty("User-Agent","Mozilla/5.0");
    c.setRequestProperty("Accept-Language","en-US,en;q=0.5");
    System.out.println(c.getResponseCode());
}catch(java.security.cert.CertificateException e){
    System.out.println("not valid");
}catch(Exception e){
    System.out.println(e.getMessage());
}

当我对无效 ssl 认证的域使用最后一个捕获时,它会抛出 java.security.cert.CertificateException: No name matching <domainName> found

但是当我尝试捕获更多工作的确切异常时,它不会编译并打印此错误:

error: exception CertificateException is never thrown in body of corresponding try statement
    }catch(java.security.cert.CertificateException e){
    ^

我如何向编译器保证这个 catch 是在正确的位置,或者我的问题是什么?

【问题讨论】:

    标签: java exception ssl


    【解决方案1】:

    当我只对具有无效 ssl 认证的域使用最后一个捕获时,它会抛出 java.security.cert.CertificateException: No name matching found

    不,它没有。它抛出一个 SSLHandshakeException 包装该异常。再看看。

    我如何保证编译器这个 catch 是在正确的位置

    你不能。它不是。编译器是正确的。

    我的问题是什么?

    正如编译器所说的那样。您正在捕获未引发的异常。取下卡扣。喜欢SSLHandshakeException就可以了。

    【讨论】:

      猜你喜欢
      • 2014-05-02
      • 1970-01-01
      • 1970-01-01
      • 2011-05-18
      • 2017-07-01
      • 2015-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多