在 Java 中,是否可以使具有 throws
语句的方法不被检查。
例如:
public class TestClass {
public static void throwAnException() throws Exception {
throw new Exception();
}
public static void makeNullPointer() {
Object o = null;
o.equals(0);//NullPointerException
}
public static void exceptionTest() {
makeNullPointer(); //The compiler allows me not to check this
throwAnException(); //I'm forced to handle the exception, but I don't want to
}
}
最佳答案
你可以尝试什么也不做:
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 所建议的那样。)子>
Unchecked exceptions in Java扩展 RuntimeException
类。 throw 它们不会要求客户提供 catch
:
// 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
声明。
还有 a word from 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.
关于java - 是否可以忽略异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16726832/