C语言异常处理
#include <iostream>#include <string>using namespace std;double divide(double a, double b, int* valid){const double delta = 0.000000000000001;double ret = 0;if( !((-delta < b) &&
·
#include <iostream>
#include <string>
using namespace std;
double divide(double a, double b, int* valid)
{
const double delta = 0.000000000000001;
double ret = 0;
if( !((-delta < b) && (b < delta)) )
{
ret = a / b;
*valid = 1;
}
else
{
*valid = 0;
}
return ret;
}
int main(int argc, char *argv[])
{
int valid = 0;
double r = divide(1, 0, &valid);
if( valid )
{
cout << "r = " << r << endl;
}
else
{
cout << "Divided by zero..." << endl;
}
return 0;
}
除法操作异常优化:
#include <iostream>
#include <string>
#include <csetjmp>
using namespace std;
static jmp_buf env;
double divide(double a, double b)
{
const double delta = 0.000000000000001;
double ret = 0;
if( !((-delta < b) && (b < delta)) )
{
ret = a / b;
}
else
{
longjmp(env, 1);
}
return ret;
}
int main(int argc, char *argv[])
{
if( setjmp(env) == 0 )
{
double r = divide(1, 0);
cout << "r = " << r << endl;
}
else
{
cout << "Divided by zero..." << endl;
}
return 0;
}
程序开始执行,setjmp(env)的意思是将程序上下文信息保存到env这个结构体,保存完后返回0。接着往下执行divide(1, 0)这个函数,由于第二个参数是0,所以执行函数内的longjmp(env, 1),这个函数的意思是此时立即停止往下执行,跳转到刚刚保存在env中的上下文中去,也就是跳转到if( setjmp(env) == 0 )这一行代码这里,并且返回1,那么if语句就进不去了,所以执行cout << “Divided by zero…” << endl;这破坏了结构化程序的三大特性!!!在工程中很少见,可读性差!
#include <iostream>
#include <string>
using namespace std;
#define SUCCESS 0
#define INVALID_POINTER -1
#define INVALID_LENGTH -2
#define INVALID_PARAMETER -3
int MemSet(void* dest, unsigned int length, unsigned char v)
{
if( dest == NULL )
{
return INVALID_POINTER;
}
if( length < 4 )
{
return INVALID_LENGTH;
}
if( (v < 0) || (v > 9) )
{
return INVALID_PARAMETER;
}
unsigned char* p = (unsigned char*)dest;
for(int i=0; i<length; i++)
{
p[i] = v;
}
return SUCCESS;
}
int main(int argc, char *argv[])
{
int ai[5];
int ret = MemSet(ai, sizeof(ai), 0);
if( ret == SUCCESS )
{
}
else if( ret == INVALID_POINTER )
{
}
else if( ret == INVALID_LENGTH )
{
}
else if( ret == INVALID_PARAMETER )
{
}
return ret;
}
对于职场新人,不大好,C++异常处理比C要好很多!
小结
更多推荐
已为社区贡献1条内容
所有评论(0)