2

想象一下我有以下方法:

public static void funcA() {...}

public static void funcB() 
{
    byteBuffer.wrap(someByteArray, 0, someByteArra.length);
}

在 JAVA API 中:

public static ByteBuffer wrap(byte[]array, int offset, int length)
{
    try {
        return new HeapByteBuffer(array, offset, length);
    } catch (IllegalArgumentException x) {
        throw new IndexOutOfBoundsException();
    }
}

函数链:funcB() -> ByteBuffer.wrap()

我的问题是 funcB 为什么不需要围绕这个抛出异常的 java api 方法执行 try-catch 块。funcB 在没有 try-catch 块的情况下编译得很好。我相信答案与 java api 方法抛出异常但未声明为“抛出 IndexOutOfBoundsException”这一事实有关

函数链:funcA() -> funcB() -> ByteBuffer.wrap(...)

我的下一个问题是,当我将funcB更改为“funcB() throws IndexOutOfBoundsException”时,为什么 funcA 不需要捕获 funcB 抛出的异常?编译器是否深入挖掘并意识到 ByteBuffer.wrap(...) 没有声明为“wrap() throws IndexOutOfBoundsException”,所以所有调用者实际上不需要捕获任何东西,甚至是子调用者(在这种情况下是 funcB)被声明为“funcB throws IndexOutOfBoundsException”?

抱歉,如果这令人困惑或难以理解。

请帮忙。

吉布

4

2 回答 2

9

IndexOutofBoundsException扩展了 RuntimeException。它是一个运行时异常,不需要检查。

请参阅未经检查的异常 - 争议。

于 2009-04-03T19:49:47.750 回答
4

异常层次结构的顶部是 java.lang.Throwable。这是一个检查异常(编译器强制你捕获它或声明你抛出它)。

在 Throwable 下面有 Exception,也是一个检查的异常,还有 Error,一个未经检查的异常(编译器不会警告你)。

在 Exception 下面有 RuntimeException,也是一个未经检查的异常。

Java 的设计者打算使用异常的方式是:

  • 例外,可能出错的事情
  • 错误,可能出错的低级事物,程序无法从中恢复
  • RuntimeException, programmer errors (like going past the end of an array, or calling a method on null).

The idea behind not having to catch unchecked exceptions is that they indicate failures (VM level, or programmer) that either you cannot handle (VM error) or should not exist in a properly debugged program (programmer mistake).

Not everyone agrees with the intent of the designers of Java on this and chose to use RuntimeException to mean things other than programmer mistake.

于 2009-04-03T20:18:27.527 回答