在代码中可能抛出多种类型的异常时,哪一段异常处理代码会被调用取决于它们所捕捉的异常类型。
http://caterpillar.onlyfun.net/Gossip/CppGossip/ExceptionHandling.html
亮点:
發生錯誤時,執行哪一段 catch 區塊是由您所丟出的資料型態而定,丟出整數時就由設定 catch 整數的區塊捕捉,丟出浮點數時就用設定 catch 浮點數 的區塊捕捉,您也可以直接丟出一個代表錯誤訊息的字串,以說明錯誤的原因,例如:
#include <iostream>
using namespace std;
int main() {
int a = 0;
int b = 0;
cout << "請輸入被除數: ";
cin >> a;
cout << "請輸入除數: ";
cin >> b;
try {
if(b == 0)
throw "發生除零的錯誤";
cout << "a / b = "
<< static_cast<double>(a) / b
<< endl;
}
catch(int err) {
cout << "除數為: " << err << endl;
cout << "結果無限大" << endl;
}
catch(const char* str) {
cerr << "錯誤: " << str << endl;
}
return 0;
}
執行結果:
|
請輸入被除數
: 9 |
HxLauncher: Launch Android applications by voice commands