php變數定義與異常處理(1/3)

來源:互聯網
上載者:User

目中把錯誤等級設定為: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來做必要的清理工作:

首頁 1 2 3 末頁

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.