异常处理:
1)throw表达式:throw引发异常条件
2)try块:try{...} catch(){...} catch(){..}模式,try块抛出异常,catch处理
3)标准库异常类
throw表达式:
Sales_item item1, item2;
std::cin >> item1 >> item2;
// first check that item1 and item2 represent the same book
if (item1.same_isbn(item2)) {
std::cout << item1 + item2 << std::endl;
return 0; // indicate success
} else {
std::cerr << "Data must refer to same ISBN"
<< std::endl;
return -1; // indicate failure
}
使用throw抛出异常:
// first check that data is for the same item
if (!item1.same_isbn(item2))
throw runtime_error("Data must refer to same ISBN");
// ok, if we're still here the ISBNs are the same
std::cout << item1 + item2 << std::endl;
问? throw使用的表达式是否可以自定义,即自定义函数来处理异常...
try块:
try {
program-statements
} catch (exception-specifier) {
handler-statements
} catch (exception-specifier) {
handler-statements
} //...
实例代码:
try
{
int t_int = 13;
char* t_str = "fesdfe";
if(t_int == 12)
throw t_int;
if(t_str != NULL)
throw t_str;
}
catch(int i_param)
{
cout<<i_param<<endl;
}
catch(char* str_param)
{
cout<<str_param<<endl;
}
注意:一旦抛出异常,就是由接收到异常的catch结束运行,即在throw t_int抛出时,执行catch(int i_param)块后接收了try catch。
根据throw出的条件,可以定义多个相应的catch
标准异常:
assert() //断言 条件为true不进行任何操作,为假抛出。
其他标准异常