📄 subject_57372.htm
字号:
<p>
序号:57372 发表者:ljl 发表日期:2003-10-24 18:01:35
<br>主题:msdn上的程序,请教
<br>内容:#include <iostream.h><BR><BR>void MyFunc( void );<BR><BR>class CTest<BR>{<BR>public:<BR> CTest(){};<BR> ~CTest(){};<BR> const char *ShowReason() const { return "Exception in CTest class."; }<BR><BR>};<BR><BR>class CDtorDemo<BR>{<BR>public:<BR> CDtorDemo();<BR> ~CDtorDemo();<BR>};<BR><BR>CDtorDemo::CDtorDemo()<BR>{<BR> cout << "Constructing CDtorDemo." << endl;<BR>}<BR><BR>CDtorDemo::~CDtorDemo()<BR>{<BR> cout << "Destructing CDtorDemo." << endl;<BR>}<BR><BR>void MyFunc()<BR>{<BR><BR> CDtorDemo D;<BR> cout<< "In MyFunc(). Throwing CTest exception." << endl;<BR> throw CTest();<BR>}<BR><BR>int main()<BR>{<BR> cout << "In main." << endl;<BR> try<BR> {<BR> cout << "In try block, calling MyFunc()." << endl;<BR> MyFunc();<BR> }<BR><BR> catch( CTest E )<BR> {<BR> cout << "In catch handler." << endl;<BR> cout << "Caught CTest exception type: ";<BR> cout << E.ShowReason() << endl;<BR> }<BR> catch( char *str )<BR> {<BR> cout << "Caught some other exception: " << str << endl;<BR> }<BR> cout << "Back in main. Execution resumes here." << endl;<BR> return 0;<BR><BR>}<BR><BR>关于异常处理的疑惑:<BR>是否catch的只是定义的exception,也就是你所能想到的,在程序中写的,比如这个程序中的 catch( CTest E )和catch( char *str ),如果别的地方还有可能的话那个异常就“无法控制了”,只能是调试的时候捕获它在写到程序里面去,可以这样理解吗?
<br><a href="javascript:history.go(-1)">返回上页</a><br><a href=http://www.copathway.com/cndevforum/>访问论坛</a></p>
<hr size=1>
<blockquote><p>
回复者:LuckGood 回复日期:2003-10-24 18:33:40
<br>内容:如果这个时候你还想捕获其他的未知的异常可以使用catch(...)来实现。<BR>try{}<BR>catch(CTest E){}<BR>catch(char* str){}<BR>catch(...){/*全部的异常*/}<BR>你查msdn,应该有关于catch(...)的介绍的。
<br>
<a href="javascript:history.go(-1)">返回上页</a><br><a href=http://www.copathway.com/cndevforum/>访问论坛</a></p></blockquote>
<hr size=1>
<blockquote><p>
回复者:ljl 回复日期:2003-10-24 19:42:31
<br>内容:try<BR>{<BR> throw CSomeOtherException();<BR>}<BR>catch(...) // Handle all exceptions<BR>{<BR> // Respond (perhaps only partially) to exception<BR> //...<BR><BR> throw; // Pass exception to some other handler<BR>}<BR><BR>这是msdn上的,当我把catch(...)放到 catch( CTest E )之前的话就会报错,放到后面就ok。<BR>我的疑问是:这些被catch到的都应该是定义好的某个exception 类,或者说你要针对可能出现的exception定义特定的类,然后在程序中引用。不知道我的表达和理解是否清楚?多谢!<BR>
<br>
<a href="javascript:history.go(-1)">返回上页</a><br><a href=http://www.copathway.com/cndevforum/>访问论坛</a></p></blockquote>
<hr size=1>
<blockquote><p>
<font color=red>答案被接受</font><br>回复者:LuckGood 回复日期:2003-10-25 16:37:48
<br>内容:yes.<BR>如果你try的代码里面没有抛出(throw)异常,那你的所有catch都白搭.catch到的异常都是在try代码段中抛出的.我想基本上常见的异常类都已经实现了,无需你再写,如果需要,自己当然可以自定义. 代码中可能抛出各种各样的异常,可以是简单数据,如int,char;也可以是一个类的实例(引用).
<br>
<a href="javascript:history.go(-1)">返回上页</a><br><a href=http://www.copathway.com/cndevforum/>访问论坛</a></p></blockquote>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -