Re: [閒聊] 尋求比nest-if更優美的解決辦法
以前寫COM的程式每次都要檢查HRESULT,
那時候所有的code都是用這個 pattern...
throw 和 catch 的部分還可以再多加功能
這樣錯誤發生時, 程式檔名,行數,call stack資訊都有了
#define TEST_RESULT(method) \
{ int ret = method; \
if (ret != 0) \
ThrowSomeException(ret, __FILE__, __LINE__, "Some message..."); }
int MyFunction()
{
try
{
TEST_RESULT( checkData(data) );
TEST_RESULT( modifyData(data) );
TEST_RESULT( fireDataChanged(data) );
TEST_RESULT( saveDataIntoFile(data) );
}
catch (SomeException& e)
{
return e.ErrorCode
}
}
※ 引述《legnaleurc (CA)》之銘言:
: 如果是 C++ 的話 ... 我通常是用 exception 說
: if( data == NULL ) {
: // error return
: }
: try {
: checkData( data );
: modifyData( data );
: fireDataChanged( data );
: saveDataIntoFile( data );
: } catch( DataInvalidError & e ) {
: // do some roll back thing
: } catch( std::exception & e ) {
: // what ever error
: }
: // here should be fine
: 呃, 本質上也是利用類似 setjump 的效果啦
: 純 C 的話 ... 我應該也是會用連串的 if-else
: 雖然說彈性有比較差, 但是不會想要再增加
: function pointer array 或是 State Pattern 的複雜度
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 75.18.242.155
→
12/07 19:52, , 1F
12/07 19:52, 1F
→
12/07 19:52, , 2F
12/07 19:52, 2F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 13 之 21 篇):