如果调用函数出现错误并不直接返回错误代码,用CV_ERROR宏调用cvError函数,然后在cvError中调用error函数来报告错误信息.
在进入error函数之前,新建一个错误异常类,来保存当前的错误信息,然后利用这个异常类作为error函数的接口.
在error函数内,首先检测是否存在自定义的错误处理器,若存在则进入自定义的错误处器处理错误,否则,报告错误信息,并抛出错误异常.
若在错误处理处,有异常的捕获,则可以捕获该异常,用户进行相应的处理.
CV_ERROR(宏定义)-->error(函数)-->exception类-->异常处理
#define CV_ERROR( Code, Msg ) \ 2 { \ 3 cvError( (Code), cvFuncName, Msg, __FILE__, __LINE__ ); \ 4 __CV_EXIT__; \ 5 } 6 CV_IMPL void cvError( int code, const char* func_name, const char* err_msg, const char* file_name, int line ) 7 { 8 cv::error(cv::Exception(code, err_msg, func_name, file_name, line)); 9 } 10 void error( const Exception& exc ) 11 { 12 if (customErrorCallback != 0) //检测是否存在自定义的错误处理器 13 customErrorCallback(exc.code, exc.func.c_str(), exc.err.c_str(), 14 exc.file.c_str(), exc.line, customErrorCallbackData); 15 else 16 { 17 //报告错误信息 18 const char* errorStr = cvErrorStr(exc.code); 19 char buf[1 << 16]; 20 sprintf( buf, "OpenCV Error: %s (%s) in %s, file %s, line %d", 21 errorStr, exc.err.c_str(), exc.func.size() > 0 ? 22 exc.func.c_str() : "unknown function", exc.file.c_str(), exc.line ); 23 fprintf( stderr, "%s\n", buf ); 24 fflush( stderr ); 25 } 26 27 if(breakOnError) 28 { 29 static volatile int* p = 0; 30 *p = 0; 31 } 32 throw exc; //抛出异常 33 }
#define CV_ERROR( Code, Msg ) \ 2 { \ 3 cvError( (Code), cvFuncName, Msg, __FILE__, __LINE__ ); \ 4 __CV_EXIT__; \ 5 } 6 CV_IMPL void cvError( int code, const char* func_name, const char* err_msg, const char* file_name, int line ) 7 { 8 cv::error(cv::Exception(code, err_msg, func_name, file_name, line)); 9 } 10 void error( const Exception& exc ) 11 { 12 if (customErrorCallback != 0) //检测是否存在自定义的错误处理器 13 customErrorCallback(exc.code, exc.func.c_str(), exc.err.c_str(), 14 exc.file.c_str(), exc.line, customErrorCallbackData); 15 else 16 { 17 //报告错误信息 18 const char* errorStr = cvErrorStr(exc.code); 19 char buf[1 << 16]; 20 sprintf( buf, "OpenCV Error: %s (%s) in %s, file %s, line %d", 21 errorStr, exc.err.c_str(), exc.func.size() > 0 ? 22 exc.func.c_str() : "unknown function", exc.file.c_str(), exc.line ); 23 fprintf( stderr, "%s\n", buf ); 24 fflush( stderr ); 25 } 26 27 if(breakOnError) 28 { 29 static volatile int* p = 0; 30 *p = 0; 31 } 32 throw exc; //抛出异常 33 }
opencv屏蔽异常的方式:
debug时,出异常;
release时,屏蔽异常;