2011-11-17 117 views
0

我非常肯定,這之前工作,但日食說,它在投擲線有錯誤。java拋出檢查異常?

try{} 
}catch(Exception e){ 
    throw e; } 

在我的老學生項目中,我寫道:

try { 
     Class.forName("org.postgresql.Driver"); 
     this.connection = DriverManager.getConnection(
       DataSource.getURL(), DataSource.getUserName(), DataSource.getPassword()); 
    } catch (ClassNotFoundException e) { 
     System.out.println("Could not find driver to connect to database. Please make" 
       + "sure the correseponding postgreSQLjdbc library is added."); 
     throw e; 

    } catch (SQLException e) { 
     System.out.println("Username or password is not correct"); 
     throw e; 
    } 

,它是完美的。

只有這種類型的作品,但它不是我想要的

throw new UnsupportedAddressTypeException(); 

回答

6

想必你的方法是聲明UnsupportedAddressTypeException但不SQLExceptionClassNotFoundException。檢查異常只能從聲明拋出這些異常或超類的方法拋出(包括重新拋出現有的異常)。

+0

它總是這樣嗎?我會徹底瘋狂... – Aubergine

+0

@Aubergine--它總是那樣。一個方法聲明檢查它拋出/傳播的異常的要求在1.0以後就已經在Java中,並且可能更早。你可能會發瘋:-) –

+0

我明白這一點! :-)喝咖啡時間。 – Aubergine

0

蝕說,它的錯誤,因爲:

其中包含的代碼塊需要具有一個聲明所述的方法「拋出異常」

的方法,或者需要進行異常處理本身OR信號到其它調用方法它可以拋出一個異常,他們應該處理它。

處理它的替代方法是將「throw e」放在另一個try/catch塊(處理異常本身的方法)中。

你的單碼工作,因爲它有這些語句的方法必須聲明,如:

方法X()拋出ClassNotFoundException的,的SQLException

0

沒有額外的信息與你在做什麼具體的我只能給你的通用解決方案是重新引發包裝在未經檢查的RuntimeException中的異常。

您包含的代碼會重新拋出異常,這是一個檢查的異常。除非這個引入的方法被聲明爲「throws Exception」,否則這可能無法在任何Java版本中運行。

另一方面,不要記錄和重新拋出。做一個或另一個。所以你的項目代碼應該看起來像:

.... 

    } catch (SQLException e) { 
     throw RuntimeException("Username or password is not correct", e); 
    } 
0

ClassNotFoundException或SQLException是檢查異常。因此,無論何時它們被拋出都應該被處理(即使手動使用'throw'關鍵字)。

有兩種方法可以處理已檢查的異常: 1.圍繞可能在try-catch塊內引發檢查異常的代碼。 2.在寫入特定代碼的方法定義之後添加throws子句。

現在,在這裏,當您拋出e'其中e是ClassNotFoundException或SQLException的實例時,它必須以上述兩種方式之一來處理。

但是,UnsupportedAddressTypeException是一個未經檢查的異常。所以你不需要明確地處理它。你可以把它扔到任何地方,Java會照顧它。