今天在論壇上看到一個關於異常的問題,沒看到一個正確的回帖,也許好多朋友還搞不懂這個問題,特引用過來一下:
---------------------------------------
Imagine that there are two exception classes called Exception1 and Exception2 that descend from the Exception class. Given these two class definitions,
1. class First {
2. void test() throws 1, Exception2 { . . . }
3. }
4. class Second extends First {
5. void test() { . . . }
Create a class called Third that extends Second and defines a test() method. What exceptions can Third's test method throw?
answer:no checked Exception .why?
這個答案和any Exception有什麼不同,哪位高手幫忙解釋一下,
-------------------------------------
1。首先要清楚異常的分類,異常分爲運行時異常(RuntimeException)和
受檢查異常(Checked Exception).
運行時異常(RuntimeException):是指程序員由於自己的錯誤而造成
的可避免異常。比如下標越界異常:ArrayIndexOutOfBoundsException,
這是程序員在Code的時候就能夠正常處理的,還比如除數爲0時的
ArithmeticException。
受檢查異常(Checked Exception):是指非人爲原因而造成的不可避
免的異常,比如IOException,SQLException,ClassNotFoundException...
這些異常並不是由於我們程序員自己的粗心和錯誤而造成的。這類異常必須
要用try...catch來捕獲或者聲明拋出異常。在編譯時JVM會檢查的,而
運行時異常(RuntimeException)在編譯的時候JVM是不會檢查的。
2。我們在方法重寫時所說的子類不能拋出比父類更多的異常,這裏所說的異常並
不是所有異常(any Exception),而只是受檢查異常(Checked Exception),
並不適應運行時異常(RuntimeException),比如下面這個例子:
class Sup
{
public void A() throws ArithmeticException
{
}
}
class Sub extends Sup
{
public void A() throws RuntimeException
{
}
}
在上面這個例子中在重寫父類的A()方法時拋出的異常RuntimeException是
ArithmeticException的父類,也許有些朋友以爲這是錯誤的,肯定編譯不過,
但是我很明確的告訴你上面的代碼是正確的,原因見以上所述。不信的朋友
可以自己動手編譯一下了。
看完我上面的解釋,大家應該知道答案no checked Exception就是我所
說的運行時異常(RuntimeException)。不能是所有異常(any Exception),
當然還可以是Exception1和Exception2,或者是它們的子類,只要有這個答案的話。