爪哇 - 罚球不工作的被处理
问题描述:
以此为例子异常的亚型:爪哇 - 罚球不工作的被处理
public class TestClass {
public static void test() throws SSLHandshakeException {
throw new SSLHandshakeException("I'm a SSL Exception");
}
public static void main(String[] args) throws SSLHandshakeException {
try {
test();
} catch (IOException ioe) {
System.out.println("I`m handling IO exception");
}
}
}
所以,我有我的测试方法,其中我只是抛出SSLHandshakeException
这是一个亚型IOException
。
输出为“I`m处理IO异常”。
为什么会发生这种情况?我预计我的方法会抛出SSLHandshakeException
。是否有规则catch
比throws
更重要?
我只是想因为我认为它的可读性
答
是否有一个规则,捕获比投掷更重要?
它们是两个完全不同的东西。 throws
关键字是方法签名的一部分,并且说'此方法可以引发此异常,因此每个调用者都应该明确地处理它。'
无论是否这个方法实际上抛出异常在这里是无关紧要的。
至于catch
声明。 SSLHandshakeException 是 IOException,因此它按预期捕获。
为了让你的意图,你可以写行为:
try {
test();
} catch (SSLHandshakeException sslExc) {
throw sslExc;
} catch (IOException ioe) {
System.out.println("I`m handling IO exception that is not an SSLHandshakeException");
}
编辑:你说你觉得这不太可读。但说实话,这只是最好的方式。如果它会按照你提出的方式行事,那么你将永远无法在一个可能抛出它的方法中捕获到SSLHandshakeException?如果你想在某些条件下捕捉它,但把它扔到其他地方呢?这只会太有限而且不直观。
另一种方法就是这样;但在我看来,这是更不可读:
try {
test();
} catch (IOException ioe) {
if(ioe instanceof SSLHandshakeException)
throw ioe;
System.out.println("I`m handling IO exception that is not an SSLHandshakeException");
}
答
那是因为你打印您的自定义字符串,而不是例外的消息可能是避免使用
try {
test();
} catch (SSLHandshakeException se) {
throw se;
} catch (IOException ioe) {
System.out.println("I`m handling IO exception");
}
。试试这个:
public static void main(String[] args) throws SSLHandshakeException {
try {
test();
} catch (IOException ioe) {
System.out.println("I`m handling IO exception");
System.out.println(ioe.getMessage());
}
}
答
SSLHandshakeException
是javax.net.ssl.SSLException
至极的子类是java.io.IOException
一个子类。
所以这个代码:
public static void main(String[] args) throws SSLHandshakeException {
try {
test();
} catch (IOException ioe) {
System.out.println("I`m handling IO exception");
}
}
将捕获并IOException异常,从而打印出消息 “我真的处理IO异常”。
好吧,我现在明白了。事情是我需要我的主要方法(在这种情况下)知道如何处理SSLHandshakeException以外的IOException,并将此响应传递给其他调用方法。 –
我根据您编辑的问题进行了编辑。如果您需要捕捉的异常是IOException的其他子类,那将是理想的。然后,你可以抓住那些和ssl例外将通过。否则,这是要走的路。 – RobCo