異常處理的九條建議,你知道幾條?
合理運用異常機制,能夠顯著提升代碼的健壯性,確保程序在面對各種意外情況時仍能保持穩(wěn)定運行。
我們一起來看下這9條建議。
1. 僅在異常情況下使用異常
避免將異常用于普通控制流。
例如,不應(yīng)使用異常來終止循環(huán)控制流:
try{
Iterator<Foo> iter =...;
while(true) {
Foo foo = i.next();
...
}
} catch (NoSuchElementException e){
}
而應(yīng)使用常規(guī)的集合迭代方式:
for(Iterator<Foo> iter =...; i.hasNext();){
Foo foo = i.next();
...
}
換句話說,不要故意寫異常,該檢查的時候先檢查,比如必要的空值檢查,不要出現(xiàn)NullPointerException。
2. 對可恢復(fù)的情況使用受檢異常,對編程錯誤使用運行時異常
在大多數(shù)情況下,如果調(diào)用者能夠恢復(fù)異常,則應(yīng)使用受檢異常。否則,應(yīng)使用運行時異常。
運行時異常表示可通過檢查某些前置條件(如數(shù)組邊界和空值檢查)來避免的編程錯誤。
在以下方法中,IllegalArgumentException是一個運行時異常,其用法表明存在編程錯誤。
通??梢酝ㄟ^檢查前置條件來避免此類錯誤,例如在此處檢查hasNext()方法。
/**
* 將標(biāo)簽字符串轉(zhuǎn)換為標(biāo)簽映射。
*
* @param tagString 以空格分隔的鍵值對字符串。例如,{@code "key1=value1 key_n=value_n"}
* @return 標(biāo)簽{@link Map}
* @throws IllegalArgumentException 如果標(biāo)簽字符串已損壞。
*/
public static Map<String, String> parseTags(final String tagString) throws IllegalArgumentException {
// 按空格或'='分隔
Scanner scanner = new Scanner(tagString).useDelimiter("\\s+|=");
Map<String, String> tagMap = new HashMap<String, String>();
try {
while (scanner.hasNext()) {
String tagName = scanner.next();
String tagValue = scanner.next();
tagMap.put(tagName, tagValue);
}
} catch (NoSuchElementException e) {
// 標(biāo)簽字符串已損壞。
throw new IllegalArgumentException("無效的標(biāo)簽字符串 '" + tagString + "'");
} finally {
scanner.close();
}
return tagMap;
}
3. 避免不必要地使用受檢異常
受檢異常會強制調(diào)用者處理異常情況,因為如果不處理,編譯器會報錯。
過度使用受檢異常會給調(diào)用者帶來處理異常情況的負(fù)擔(dān)。
因此,應(yīng)僅在必要時使用受檢異常。
當(dāng)無法通過檢查前置條件來避免異常,并且調(diào)用者可以采取一些有用的操作來處理該異常時,使用受檢異常。
常用的運行時異常本身就是不過度使用受檢異常的示例。
常見的運行時異常包括:ArithmeticException、ClassCastException、IllegalArgumentException、IllegalStateException、IndexOutOfBoundExceptions、NoSuchElementException和NullPointerException。
在以下方法中,當(dāng)propertyName不是目標(biāo)情況之一時,調(diào)用者無能為力,因此拋出一個運行時異常。
@Override
public Object get(String propertyName) {
switch (propertyName.hashCode()) {
case 1:
return marketDataName;
case 2:
return parameterMetadata;
case 3:
return order;
case 4:
return currency;
case 5:
return sensitivity;
default:
throw new NoSuchElementException("未知屬性: " + propertyName);
}
}
4. 優(yōu)先使用標(biāo)準(zhǔn)異常
常用的異常包括:
- java.io.IOException
- java.io.FileNotFoundException
- java.io.UnsupportedEncodingException
- java.lang.reflect.InvocationTargetException
- java.security.NoSuchAlgorithmException
- java.net.MalformedURLException
- java.text.ParseException
- java.net.URISyntaxException
- java.util.concurrent.ExecutionException
- java.net.UnknownHostException
標(biāo)準(zhǔn)異常是JDK提供給我們的小寶藏,根據(jù)名字我們就能夠知道異常原因,而且,大家共用一套異常,也便于溝通。
5. 拋出與抽象級別相適應(yīng)的異常
此條建議說的是異常轉(zhuǎn)換(捕獲一個異常并拋出另一個異常)和異常鏈接(將一個異常包裝在新異常中以保持異常的因果鏈)。
private void serializeBillingDetails(BillingResult billingResult,
BillingDetailsType billingDetails) {
try {
final JAXBContext context = JAXBContext.newInstance(BillingdataType.class);
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final Marshaller marshaller = context.createMarshaller();
marshaller.setProperty("jaxb.formatted.output", Boolean.FALSE);
final BillingdataType billingdataType = new BillingdataType();
billingdataType.getBillingDetails().add(billingDetails);
marshaller.marshal(factory.createBillingdata(billingdataType), out);
final String xml = new String(out.toByteArray(), "UTF-8");
billingResult.setResultXML(xml.substring(
xml.indexOf("<Billingdata>") + 13,
xml.indexOf("</Billingdata>")).trim());
billingResult.setGrossAmount(billingDetails.getOverallCosts()
.getGrossAmount());
billingResult.setNetAmount(billingDetails.getOverallCosts()
.getNetAmount());
} catch (JAXBException | UnsupportedEncodingException ex) {
throw new BillingRunFailed(ex);
}
}
上述方法捕獲JAXBException和UnsupportedEncodingException,并重新拋出一個與方法抽象級別相適應(yīng)的新異常。
新的BillingRunFailed異常包裝了原始異常。異常鏈接的好處是保留了有助于調(diào)試問題的低級異常。
建議很多新手、老手聽一下這條建議。異常轉(zhuǎn)換是為了返回的異常更容易理解,明確異常本質(zhì);但是轉(zhuǎn)換后不要丟棄了原始異常,在Debug或排錯的時候,如果丟失了原始異常,很容易懵~~
6. 為每個方法拋出的所有異常編寫文檔
這一點被嚴(yán)重忽視。大多數(shù)公共API都缺少@throws Java文檔來解釋所拋出的異常。
...
*
* @throws MalformedURLException 下級目錄的正式系統(tǒng)標(biāo)識符無法轉(zhuǎn)換為有效URL。
* @throws IOException 讀取下級目錄文件時出錯。
*/
public String resolveSystem(String systemId)
throws MalformedURLException, IOException {
...
下面這個是缺少關(guān)于在何種情況下拋出異常信息的壞示例。
* @throws Exception 異常
*/
public void startServer() throws Exception {
if (!externalDatabaseHost) {
這一條是個好建議,但是不容易實現(xiàn)。如果是想實現(xiàn)一些基礎(chǔ)組件,或者是開源項目,就要有完善的文檔了。
7. 在詳細(xì)消息中包含故障捕獲信息
private OutputStream openOutputStream(File file) throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("文件 '" + file + "' 已存在但為目錄");
}
if (!file.canWrite()) {
throw new IOException("文件 '" + file + "' 不可寫");
}
} else {
final File parent = file.getParentFile();
if (parent!= null) {
if (!parent.mkdirs() &&!parent.isDirectory()) {
throw new IOException("目錄 '" + parent + "' 無法創(chuàng)建");
}
}
}
return new FileOutputStream(file, false);
}
在此方法中,IOException使用不同的字符串來傳遞不同的故障捕獲信息。
這條建議同樣適用于日志或接口異常信息,看過很多接口返回的是“服務(wù)異常,請稍后再試”,返回了一句沒有太多幫助的信息。
理性的說,如果返回錯誤,那就是有異常了。很多時候,應(yīng)該包含一些有用的信息,比如,缺少必填參數(shù)xxx。
8. 力求故障原子性
這條建議關(guān)于失敗的。
一般來說,失敗的方法不應(yīng)更改方法中對象的狀態(tài)。
為了盡早失敗,一種方法是在執(zhí)行操作之前檢查參數(shù)的有效性,若無效則立即拋出異常,避免執(zhí)行可能導(dǎo)致狀態(tài)改變的操作。。比如:
/**
* 將新的整數(shù)值分配給緩沖區(qū)實例的位置索引。
* @param index int
* @param newValue int
*/
public void modifyEntry(int index, int newValue) {
if (index < 0 || index > size - 1) {
throw new IndexOutOfBoundsException();
}
// ((int[]) bufferArrayList.get((int) (index / pageSize)))[index % pageSize] =
((int[]) bufferArrayList.get((index >> exp)))[index & r] =
newValue;
}
如果無法前置檢查,就在失敗時將對象恢復(fù)到操作前的狀態(tài),避免產(chǎn)生不一致的數(shù)據(jù)。
9. 不要忽略異常
不要空 catch 異常塊,應(yīng)根據(jù)異常的性質(zhì)進行適當(dāng)處理,如記錄日志、提供友好的錯誤提示給用戶、進行錯誤恢復(fù)操作或重新拋出更合適的異常等。
public static Bundle decodeUrl(String s) {
Bundle params = new Bundle();
if (s!= null) {
String array[] = s.split("&");
for (String parameter : array) {
String v[] = parameter.split("=");
try {
params.putString(URLDecoder.decode(v[0], "UTF-8"), URLDecoder.decode(v[1], "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
return params;
}
該說不說,printStackTrace方法和空catch一樣差勁。