首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

抛出错误throw

2012-05-06 
抛出异常throwthrow语句是不是一定要在try语句内? 我写在外面就会报错 为什么一定要在try里面[解决办法]MS

抛出异常throw
throw语句是不是一定要在try语句内? 我写在外面就会报错 为什么一定要在try里面

[解决办法]
MSDN上的一个Demo例子

C/C++ code
// exceptions_trycatchandthrowstatements2.cpp// compile with: /EHsc#include <iostream>using namespace std;void MyFunc( void );class CTest {public:   CTest() {};   ~CTest() {};   const char *ShowReason() const {       return "Exception in CTest class.";    }};class CDtorDemo {public:   CDtorDemo();   ~CDtorDemo();};CDtorDemo::CDtorDemo() {   cout << "Constructing CDtorDemo.\n";}CDtorDemo::~CDtorDemo() {   cout << "Destructing CDtorDemo.\n";}void MyFunc() {   CDtorDemo D;   cout<< "In MyFunc(). Throwing CTest exception.\n";   throw CTest();}int main() {   cout << "In main.\n";   try {       cout << "In try block, calling MyFunc().\n";       MyFunc();   }   catch( CTest E ) {       cout << "In catch handler.\n";       cout << "Caught CTest exception type: ";       cout << E.ShowReason() << "\n";   }   catch( char *str )    {       cout << "Caught some other exception: " << str << "\n";   }   cout << "Back in main. Execution resumes here.\n";}
[解决办法]
楼主最好是先查阅一下C++书籍中论述异常的章节。不用太难的书,一般入门的如C++ Primer就行。

一个被抛出的异常总是需要被捕捉,也就是被catch。你有了catch就肯定是会有try。至于try写在哪一层,无所谓。如果一直都没有catch——也就是你说的“写在外面”,那么异常就会被抛出main函数,这时程序就会调用std::terminate(),看上去就是你说的“出错了”。

热点排行