try catch的學習使用
最近在使用VC2010進行項目開發,使用visa庫和儀器驅動進行儀器儀表的程控操作,在每次執行完一次操作之後,都需要判斷該操作是否正確執行,如果正確執行,則僅需往下執行,如果指令執行錯誤則返回-1並跳出函數。
開始使用下面的方式進行判斷;
int result = SystemWrite(cmd1,……);
if (result < 0)
{
return -1;
}
int result = SystemWrite(cmd2,……);
if (result < 0)
{
return -1;
}
對於每一條指令都是用下面的方式進行判斷,造成的結果是,代碼行太多,看着密密麻麻一大片,並且可讀性差。後來瞭解到C++的try{……}catch(){……}
異常捕獲功能,通過學習,做了下面的函數進行測試。
#include "stdafx.h"
void checkError(int resultState)
{
if (resultState < 0)
{
throw ("命令執行錯誤,請檢查!");
}
}
int _tmain(int argc, _TCHAR* argv[])
{
try
{
checkError(1);
checkError(0);
checkError(-1);
checkError(5);
}
catch (const char *err_msg)
{
printf("CMemoryException \n");
}
return 0;
}
這樣在對命令執行情況進行判斷的時候就變得簡單了,如下
try
{
checkError(SystemWrite(cmd1,……));
checkError(SystemWrite(cmd2,……));
checkError(SystemWrite(cmd3,……));
}
catch (const char *err_msg)
{
return -1;
}
由於此處只謝了2條指令,所以感官上卻別不是特別大,但是當命令增加到十幾二十幾條的時候,感覺就特別明顯了。
注意:
此處是通過定義個函數來對參數檢查的,缺點是會增加很多函數的調用過程,可以修改爲帶參數的宏定義的形式進行,不過博主此處沒有進行嘗試。