/ / exceptions_trycatchandthrowstatements.cpp // compile with: /EHsc #include <iostream> using namespace std; int main() { char *buf; try { buf = new char[512]; if( buf == 0 ) throw "Memory allocation failure!"; } catch( char * str ) { cout << "Exception raised: " << str << '/n'; } // ... return 0; } 1 楼 小土人 - 03月27日 - 11时59分 // 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 << "Constructin* **torDemo./n"; } CDtorDemo::~CDtorDemo() { cout << "Destructin* **torDemo./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"; return 0; } 2 楼 小土人 - 03月27日 - 12时01分 // exceptions_trycatchandthrowstatements3.cpp #include <iostream> using namespace std; void empty() throw() { puts("In empty()"); } void with_type() throw(int) { puts("Will throw an int"); throw(1); } int main() { try { empty(); with_type(); }catch (int){ puts("Caught an int"); } }