[英]why it couldn't catch exception in c++?
我寶貴的朋友們;
為什么 c++ 在這個例子中無法捕捉到異常? 你能解釋一下嗎? 我試了很多但還是不行。 如果我在 cmd 中輸入一個字符,則 catch 塊不起作用。
try {
int dX = 0;
cin >> dX;
dX = static_cast<double>(10 / dX);
cout << dX << endl;
}
catch (conts std::exception &exp) { // if I input any of chars, it doesn't catch?
cerr << "Error: " << exp->what() << endl;
}
您所做的事情不會引發異常,因此您可以捕獲任何東西。 錯誤(並且可能引發了較低級別的異常),但是您不能使用處理程序來管理它。
其他日子會遇到這樣的例外情況:
try
{
}
catch (const std::exception& error)
{
// handler
}
你們的代碼都不會拋出異常。
這就是為什么它沒有被捕獲(因為沒有)。
通常你想檢查讀取操作的 state 以確保它明確地工作。
int dX = 0;
if (cin >> dX) {
// Read worked.
dX = static_cast<double>(10 / dX);
cout << dX << endl;
}
else {
// Read failed.
cerr << "Error: Read of number failed\n";
}
以上是正常的處理方式。
但是你可以讓 stream 拋出異常。
// cin will throw on a read failure.
cin.exception(std::ios::fail);
try {
int dX = 0;
cin >> dX; // now this will throw if the input is not numeric.
dX = static_cast<double>(10 / dX);
cout << dX << "\n";
}
catch (std::exception const& exp) {
cerr << "Error: " << exp.what() << "\n";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.