?? 21-6.txt
字號:
/* 范例:21-6 try...catch...__finally */
#include <iostream.h>
#include <string.h>
#include <windows.h>
class Exception
{
public:
Exception(char* s = "Unknown"){ what = strdup(s); }
Exception(const Exception& e ){ what = strdup(e.what); }
~Exception(){ free(what); }
char* msg() const { return what; }
private:
char* what;
};
int main()
{
float e, f, g;
try
{
try
{
f = 1.0;
g = 0.0;
try
{
e = f / g;
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
throw(Exception("Can't Divide by 0"));
}
}
catch(const Exception& e)
{
cout << "捉住一個C++例外" << '\n' << e.msg() << endl;
}
}
__finally
{
puts("即使處理完try區塊中的例外,仍會執行__finally區塊");
}
getchar();
return 0;
}
程序執行結果﹕
project p21-6.exe raised exception class EZeroDivide with message 'Floating point division by zero'. Process stopped. Use Step or Run to continue
除以0時會產生無限大的整數,這是在logic_error(邏輯錯誤) 中的out_of_range error,請讀者特別注意,看到這信息后再編譯一次就可以看到你所輸入的注釋,如下。
捉住一個C++例外
Can't Divide by 0
即使處理完try區塊中的例外,仍會執行__finally區塊
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -