java - 异常 CertificateException 永远不会在相应的 try 语句的主体中抛出

标签 java exception ssl

我正在尝试使用 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 证书的域上使用最后一个 catch 时,它会抛出 java.security.cert.CertificateException: No name matching <domainName> found

但是当我 try catch 更多作品的确切异常时,它不会编译并打印此错误:

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

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

最佳答案

when I use just the last catch on domains with invalid ssl certification, it throws java.security.cert.CertificateException: No name matching found

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

how can I assure compiler that this catch is in the right place

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

what's my problem?

正如编译器所说的那样。您正在捕获未抛出的异常。取下 Hook 。如果愿意,捕获 SSLHandshakeException

关于java - 异常 CertificateException 永远不会在相应的 try 语句的主体中抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27211606/

相关文章:

c# - Java 中 Calendar.get() 方法的 C# 等效项是什么?

swift - 通过 super.validateMenuItem( :) generates Swift exception

python - "cheap exceptions"是解释型语言的典型值吗?

ssl - 带有 haproxy ssl 终止的 Ejabberd

ssl - 如何强制 'OpenConnect' 客户端使用 TLS 1.0

docker - 无法访问使用 Nginx 服务 Dockerized VueJS 应用程序并导致 SSL 错误

Java:套接字还是 RMI?

java - JTable+JDBC : Easiest way

Java LinkedList——检索对象的索引

java - 使用 Zip4j : Probably not a zip file or a corrupted zip file 在 Android 中创建 zipFile 时出现异常