目中把錯誤等級設定為:error_reporting(e_all | e_strict);
陣列變數未定義也會報錯,其實挺好的,但有時候真的不需要報該錯誤,php教程的解決辦法是:
@$_get['unkown'];
這樣就可以放置該錯誤提示出來了.
exception:
throw new exception("username already taken");
更甚的情況,如果你認為用戶端並不想用過多的操作而僅僅想看到異常資訊,你可以拋出一個unchecked exception:
throw new runtimeexception("username already taken");
另外,你可以提供一個方法來驗證該username是否被佔用。
很有必要再重申一下,checked exception應該讓用戶端從中得到豐富的資訊。要想讓你的代碼更加易讀,請傾向於用unchecked excetpion來處理常式中的錯誤(prefer unchecked exceptions for all programmatic errors)。
4. document exceptions.
你可以通過javadoc’s @throws 標籤來說明(document)你的api中要拋出checked exception或者unchecked exception。然而,我更傾向於使用來單元測試來說明(document)異常。不管你採用哪中方式,你要讓用戶端代碼知道你的api中所要拋出的異常。這裡有一個用單元測試來測試indexoutofboundsexception的例子:
public void testindexoutofboundsexception() {
arraylist blanklist = new arraylist();
try {
blanklist.get(10);
fail("should raise an indexoutofboundsexception");
} catch (indexoutofboundsexception success) {}
}
上邊的代碼在請求blanklist.get(10)的時候會拋出indexoutofboundsexception,如果沒有被拋出,將 fail("should raise an indexoutofboundsexception")顯示說明該測試失敗。通過書寫測試異常的單元測試,你不但可以看到異常是怎樣的工作的,而且你可以讓你的代碼變得越來越健壯。
下面作者將介紹界中使用異常的最佳實務(best practices for using exceptions)
1. 總是要做一些清理工作(always clean up after yourself)
如果你使用一些資源例如資料庫教程串連或者網路連接,請記住要做一些清理工作(如關閉資料庫連接或者網路連接),如果你的api拋出unchecked exception,那麼你要用try-finally來做必要的清理工作: