捕获预定义的int异常 [英] Catch an pre-defined int exception
本文介绍了捕获预定义的int异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我定义了一个简单的int错误代码:
#define my_error 20
在我的代码中,我抛出此错误:
throw my_error;
现在我想尝试捕获此异常:
try
{
...
...
}
catch(my_error)
{
cout<< 错误:我的错误;不幸的是,编译器不认可这一点:
$ b
- 语法错误:'constant'
- catch处理程序必须指定一种类型
- try'block line on line'34'has no catch handlers
有办法吗?
感谢。
解决方案
/ code>不是一个类型,所以你不能抓住它。你可以做的是过滤
catch
块中的值:catch(int exception)
{
if(exception == 20)
cout< 错误:我的错误;
}
更好的方法是定义自己的异常:
class MyException:public std :: exception
{
}
// .. 。
try
{
throw MyException();
}
catch(MyException& ex)
{
}
I have defined a simple int error code:
#define my_error 20
Somewhere in my code i throw this error:
throw my_error;
Now i want to try and catch this exception thrown:
try { ... ... } catch (my_error) { cout << "Error: my error"; }
Unfortunately the compiler doesn't approve this:
- syntax error : 'constant'
- catch handlers must specify one type
- 'try' block starting on line '34' has no catch handlers
Is there a way to do this ?
Thanks.
解决方案
20
is not a type, so you can't catch it. What you can do is filter the values in thecatch
block:catch (int exception) { if ( exception == 20 ) cout << "Error: my error"; }
An even better approach would be to define your own exception:
class MyException : public std::exception { } //... try { throw MyException(); } catch(MyException& ex) { }
这篇关于捕获预定义的int异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文