asp.net Throw new exception詳細應用說明

來源:互聯網
上載者:User

throw new exception

  曾經看過有人在簡單的函數內瘋狂的使用throw new 參與商務邏輯。比如,以下代碼:

catch(exception ex)
{
  string error = ex.message;
}

public object dosomething(string username)
{
try
{
if (string.isnullorempty(username))
{
throw new exception("使用者名稱不可為空");
}
}
catch (exception ex)
{
return ex.message;
}
return true;
}


捕獲異常以後,再拋出一個新的異常。再拋出新異常之前,你可以對前面捕獲的異常做一些操作,比如記錄日誌、擷取異常資訊然後寫到新異常中

int num = convert.toint32(textbox1.text);
try
{
    if (num == 0)
    {
        throw new argumentnullexception("出現0!");
    }
    if (num == 1)
    {
        throw new exception("出現一!");
    }
}
catch (argumentnullexception ex)
{
    messagebox.show(ex.message);
}
catch (exception ex)
{
    messagebox.show(ex.message);
}

   catch是用來處理錯誤,就是發生了錯誤時,會執行catch部分.注意:是"發生了錯誤時".

  但是, 在沒有發生錯誤時, 你自己想引發錯誤怎麼辦呢? 可以使用throw語句來手工引發一個錯誤.


拋出不該拋出的exception

  上文中的dosomething函數如果在catch時不進一步封裝,直接把excepiton拋到ui層,又或者直接顯示給客戶。如果異常堆棧中提示某些敏感性資料。比如sql查詢語句、webservice uri或post資訊等。這些敏感資訊應該永遠不讓客戶知道,暴露出這些資訊有可能對系統造成潛在安全隱患!

  三、更好的利用exception

  在實際的開發中,既然拋出了exception那麼我們應該為exception提供儘可能多的關於異常本身的有用資訊。如何為拋出的異常提供更多的有用資訊呢?請看以下代碼:

public static void executecommand(action<idbcommand> action, ref string errmsg)
{
using (var connection = new sqlconnection("資料庫教程連接字串"))
{
var cmd = connection.createcommand();
try
{
action(cmd);
cmd.executenonquery();
}
catch (dbexception ex) //注意這裡將dbexception catch住
{
errmsg = ex.message;
var parameters = new dictionary<string, object>();
foreach (sqlparameter p in cmd.parameters)
parameters.add(p.parametername, p.value);

//儘可能擷取與exception相關的有用資訊,這裡只是用sqlparameter舉例而已。

//todo:(將 parameters 與 ex 對象儲存或者進一步處理)

}
catch (exception ex)
{
//todo 其他的異常處理
}
finally
{
cmd.dispose();
}
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.