Run*_*oro 27 java exception-handling exception
在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
}
}
Run Code Online (Sandbox Code Playgroud)
acd*_*ior 55
你可以尝试什么都不做:
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 */ }
}
Run Code Online (Sandbox Code Playgroud)
请记住,在现实生活中,这是非常不明智的.这可以隐藏错误并让你整整一周都在寻找狗,而这个问题实际上是一只猫(ch).(来吧,至少放一个System.err.println()- 记录是最好的做法,正如@BaileyS所建议的那样.)
Java中未经检查的异常扩展了RuntimeException该类.投掷他们不会要求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();
}
Run Code Online (Sandbox Code Playgroud)
扩展的类RuntimeException也不需要throws声明.
并从Oracle一句话吧:
这是底线指南:如果可以合理地期望客户端从异常中恢复,则将其作为已检查的异常.如果客户端无法执行任何操作以从异常中恢复,请将其设置为未经检查的异常.