java - 是否可以忽略异常?

标签 java exception exception-handling

在 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/

相关文章:

java - 列为 O(log(n))

c++ - 自包含应用程序中的异常安全

c++ - 使用枚举处理错误

android - 处理 Android 中未处理的异常

java - jOOQ 字段<T> = DSL.any(DSL.val(T...))

java - Jackson YAML - 将 null 序列化为空值

C#: 未找到方法异常(缺少 Setter)

c# - 我可以用 throw 移除空捕获吗?

java - Java异常层次结构背后的基本原理

java - 共享首选项帮助。如何保存 int?