为什么要通过参考工作抛出异常 [英] why should throwing an exception by reference work

查看:48
本文介绍了为什么要通过参考工作抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它不应该,因为参考对象在堆栈框架中被销毁。

解决方案



puzzlecracker写道:

它不应该,因为参考对象在堆栈框架中被销毁。


这个例子中的



void bar(){

MyExcepton ex(); // MyException继承自Excetpion

Exception& exRef = ex;

throw exRef;


}


void foo(){


试试{


bar();

} catch(Exception& ex){


} catch(...){}


< blockquote class =post_quotes> void bar(){
MyExcepton ex(); // MyException继承自Excetpion


这是一个非常漂亮的函数声明。它与写作完全相同



MyException ex(void);


ReturnType FunctionName (参数列表);


你想要的是:


我的例外情况;

Exception& exRef = ex;
抛出exRef;

}

void foo(){

尝试{

吧();
} catch(Exception& ex){



这里有一个无效的引用,因为它引用的对象是
已超出范围(即已被销毁)。


如果参考有效,您可以抛出参考。例如:


int global_var = 2;


int main()

{

尝试

{


抛出global_var;

}

catch(int& i)

{

i = 7;

}

}

-Tomás


2006年5月10日星期三16:11:45 -0700,puzzlecracker写道:

它不应该,因为参考对象在堆栈框架中被销毁。




通过引用抛出异常?或者抓住它?


It shouldnt, since reference object is destroyed in the stack frame.

解决方案


puzzlecracker wrote:

It shouldnt, since reference object is destroyed in the stack frame.


in this example

void bar(){
MyExcepton ex(); //MyException inherits from Excetpion
Exception &exRef=ex;
throw exRef;

}

void foo(){

try{

bar();
}catch( Exception &ex){

}catch(...){}


void bar(){
MyExcepton ex(); //MyException inherits from Excetpion
That''s a very pretty function declaration you have there. It''s exactly the
same as writing:

MyException ex(void);

ReturnType FunctionName(ParameterList);

What you want is:

My Exception ex;
Exception &exRef=ex;
throw exRef;

}

void foo(){

try{

bar();
}catch( Exception &ex){


You have an invalid reference here, because the object to which it refers
has gone out of scope (i.e. has been destroyed).

You could throw a reference if it''s valid. For example:

int global_var = 2;

int main()
{
try
{

throw global_var;
}
catch (int &i)
{
i = 7;
}
}
-Tomás


On Wed, 10 May 2006 16:11:45 -0700, puzzlecracker wrote:

It shouldnt, since reference object is destroyed in the stack frame.



Throwing an exception by reference? Or catching it?


这篇关于为什么要通过参考工作抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆