【问题标题】:Unable to throw Exception, why? [closed]无法抛出异常,为什么? [关闭]
【发布时间】:2013-09-16 20:13:55
【问题描述】:

在第一个 catch 块中,为什么我们不能抛出 Exception 对象?这里RuntimeException 工作正常。

public class CirEx {
    public Circle getCircle(int id) {
        Connection conn = null;
        try {
            Class.forName("");
            conn = DriverManager.getConnection("");
            PreparedStatement pstmt = conn.prepareStatement("");

            Circle circle = new Circle(1, "");
            return circle;
        } catch (Exception e) {
            throw new RuntimeException(e);
            // why we cann't do that.
            // throw new Exception(e);
        } finally {
            try {
                conn.close();
            } catch (SQLException e) {
                System.out.println(e);
            }
        }
    }
}

【问题讨论】:

标签: java exception-handling


【解决方案1】:

我们可以抛出Exception,前提是我们声明抛出相同的Exceptionthrows Exception 子句)或处理它(使用try catch 块)的方法。

Exception 是一个已检查异常,必须处理这些

但是

RuntimeException 之所以有效是因为它的unchecked Exception,为此我们不需要throws 子句或处理它

See Checked vs Unchecked Exception

【讨论】:

  • 你不需要声明运行时异常。
  • 我在帖子中提到过吗?为什么要投反对票?
  • 我只是想知道我的概念的原因,这就是我问这个问题的原因。
【解决方案2】:

因为在这种情况下,您必须声明您的方法会抛出异常。

 public Circle getCircle(int id) throws Exception{
Connection conn = null;
try {
    Class.forName("");
    conn = DriverManager.getConnection("");
    PreparedStatement pstmt = conn.prepareStatement("");

    Circle circle = new Circle(1, "");
    return circle;
} catch (Exception e) {
    throw new RuntimeException(e);
    // why we cann't do that.
    // throw new Exception(e);
}

finally {
    try {
        conn.close();
    } catch (SQLException e) {
        System.out.println(e);
    }
}

}

注意:RuntimeException 及其子类是特殊类型的异常,不需要显式捕获

【讨论】:

  • 怎么不相关?
  • 您不必声明运行时异常。
  • 这就是我所说的,并在示例中展示了抛出 RuntimeException 是完全可以的,但如果他想抛出异常,则必须声明它。
猜你喜欢
  • 1970-01-01
  • 2017-12-03
  • 1970-01-01
  • 1970-01-01
  • 2010-12-09
  • 2011-01-04
  • 1970-01-01
  • 1970-01-01
  • 2013-05-11
相关资源
最近更新 更多