且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有可能忽略异常吗?

更新时间:2022-04-17 22:01:16

你可以尝试不做任何事情:

You can try and do nothing about it:

public static void exceptionTest() {
    makeNullPointer(); //The compiler allows me not to check this
    try {
        throwAnException(); //I'm forced to handle the exception, but I don't want to
    } catch (Exception e) { /* do nothing */ }
}

请记住,在现实生活中 这是非常不好的。这可以隐藏错误,并让您一整周内寻找狗,而问题真的是一只猫(ch)。 (来吧,至少放一个 System.err.println()那里 - 记录是这里的***做法,如@BaileyS所建议的)

Bear in mind, in real life this is extemely ill-advised. That can hide an error and keep you searching for dogs a whole week while the problem was really a cat(ch). (Come on, put at least a System.err.println() there - Logging is the best practice here, as suggested by @BaileyS.)

Java中未检查的异常扩展了 RuntimeException 类。投掷他们不会要求客户提供 catch

Unchecked exceptions in Java extend the RuntimeException class. Throwing them will not demand a catch from their clients:

// notice there's no "throws RuntimeException" at the signature of this method
public static void someMethodThatThrowsRuntimeException() /* no need for throws here */ {
    throw new RuntimeException();
}

扩展类的RuntimeException 不需要 throws 声明。

一个来自Oracle的单词


这是底线指南:如果客户端可以合理地预期从异常中恢复,请将其作为检查的异常。如果客户端无法从异常中恢复任何东西,请将其作为未经检查的异常。

Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.