异常
#include "stdafx.h" #include <stdlib.h> #include <iostream> using namespace std; void test() { throw 5; // throw给catch了 } int main() { try { test(); } catch (int &t) { // t接受数值 cout << "int" << endl; cout << t << endl; } system("pause"); return 0; }
复杂一点的:
class Exception { public: virtual void say()=0; };
#pragma once #include "Exception.h" #include <iostream> using namespace std; class StackException:public Exception { public: void say() { cout << "StackException" << endl; } };
// Test.cpp: 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <stdlib.h> #include <iostream> #include "StackException.h" using namespace std; void test() { throw StackException(); } int main() { try { test(); } catch (Exception &e) { e.say(); } system("pause"); return 0; }