64,637
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
void log(const char * file, const char * func, int line)
{
std::cout << "exception: " << file << ":" << func << ":" << line << std::endl;
}
#define TRY \
try \
{
#define CATCH_TYPE(type) \
} \
catch (type & e) \
{ \
log(__FILE__, __FUNCTION__, __LINE__);
#define CATCH_ALL \
} \
catch (...) \
{ \
log(__FILE__, __FUNCTION__, __LINE__);
#define CATCH_END \
}
int main(int argc, char * argv[])
{
{
TRY
throw int();
CATCH_TYPE(int)
std::cout << "catch a exception" << std::endl;
CATCH_END
}
{
TRY
throw int();
CATCH_ALL
std::cout << "catch a exception" << std::endl;
CATCH_END
}
return(0);
}
有些函数在遇到异常操作时,会使用抛出处理(throw),这时你调用该函数
时,就需要用到try catch 来拦截这些抛出(throw)。
void Test(bool Throw)
{
if (Throw)
throw Exception("throw in funtion Test.");
}
void main()
{
try {
Test(true);
}
catch(Exception& e) {
ShowMessage(e.Message);
}
}
try…catch语句形式如下:
try
{
语句; //说明抛出异常的部位,该部位含有抛出异常的语句,
//如调用抛出异常的方法。
}
catch (异常类1 变量名) //按抛出的异常类进行捕获,并加处理
{
catch 处理
}
catch (异常类2 变量名)//按抛出的异常类进行捕获,并加处理
{
catch 处理
}
[finally 语句]
当catch前面的try块中发生了一个异常,try-catch语句就会自动在try块后面的各个catch块中,找出与该异常类相匹配的参数。当参数符合以下三个条件之一时,就认为这个参数与产生的异常相匹配:
(1)参数与产生的异常属于一个类;
(2)参数是产生的异常的超类;
(3)参数是一个接口时,产生的异常实现了这一接口。
当产生的异常找到了第一个与之相匹配的参数时,就执行包含这一参数的catch语句中的Java代码,执行完catch语句后,程序恢复执行,但不会回到异常发生处继续执行,而是执行try-catch结构后面的代码。