I'm CaLendarW Blog

Understanding Exception

by on Mar.29, 2009, under coding snippet, diary

Exception – 從來都被初哥覺得係個麻煩既來源, 但其實佢只係一個提醒工具, 話比大家知那裡有問題.

好多課程, 以及書本都有教點處理 Exception, 但如何正確使用 Exception 就好似得 Pragmatic Programmer 一書內有提及.

通常我使用 Exception 既地方會有以下幾個, 作用係提醒返 d 唔正常既動作, 因為唔 throw 既話, 使用者 (包括自己) 都會唔知或者唔記得:

1. Design By Contract
主要用 Exception 黎 validate 所有 input 或 pre-condition, 令佢有個 Valid State 比佢 perform action

public void Cancel()
{
    if (item.IsLoaning)
        throw new InvalidOperationException("Please return the loan before cancel");
}

2. Supporting of Share Module

public static IDbDataAdapter CreateDbDataAdapter(IDbCommand command)
{
    IDbDataAdapter adapter = null;
    if (command is SqlCommand)
    {
        adapter = new SqlDataAdapter((SqlCommand)command);
    }
    if (command is OleDbCommand)
    {
        adapter = new OleDbDataAdapter((OleDbCommand)command);
    }
    if (command is OdbcCommand)
    {
        adapter = new OdbcDataAdapter((OdbcCommand)command);
    }
    if (adapter != null)
    {
        return adapter;
    }
    throw new NotSupportedException();
}

3. Supporting on different framework

public void NewFeature()
{
#if !USING_NEW_FRAMEWORK
    throw new NotSupportedException();
#else
    doSomething();
#endif
}

4. 又或者係未做完的工作, 不過好多時都會寫 // TODO

public void DoSomething()
{
    throw new NotImplementedException();
}
:

Leave a Reply

You must be logged in to post a comment.

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!