通常,我用較高級別包裝較低級別的異常,更有意義的異常。這通常是更多的工作,但是可以讓你在層之間解耦。
想象一下,我正在編寫一個恰好從數據庫讀取的配置子系統。如果我不換,我會是這樣的:
public String getConfigurationProperty(String name) throws SQLException {
// Try to read from my configuration table
}
如果我做了包裝,我會
public String getConfigurationProperty(String name) throws ConfigurationException {
try {
// Try to read from my configuration table
} catch (SQLException ex) {
ConfigurationException wrapper = // Some subclass of ConfigurationException that wraps ex
throw wrapper;
}
}
這肯定是更多的工作。其優點是,如果在以後的時間我想改變我的配置後端,比如,基於一個一個文件,而封裝協議我的方法將成爲
public String getConfigurationProperty(String name) throws IOException {
// Try to read from my configuration file
}
然後,我將不得不改變我所有的客戶端代碼來處理IOException
s而不是SQLException
s。如果你打包,你只需要改變後端,因爲你的客戶端代碼已經寫在ConfigurationException
和它的子類中。請注意,這與您使用選中或未選中的異常無關:如果您要執行異常處理,則幾乎總是需要知道您要處理的異常類型的至少一些近似值。
現在,我傾向於這樣做。有些人認爲大多數例外無論如何都無法妥善處理,而且大部分時間這些包裝都是無稽之談。
public String getConfigurationProperty(String name) throws ConfigurationException {
try {
// Try to read from my configuration file
} catch (IOException ex) {
ConfigurationException wrapper = // Some subclass of ConfigurationException that wraps ex
throw wrapper;
}
}
是否有這些問題的標籤?關於如何大規模構建代碼的問題?我覺得這個話題非常有趣,需要一個好的論壇。 –