今天,當我的 try catch 塊沒有像我預期的那樣作業時,我感到非常驚訝。當我的 try 塊中發現錯誤時,我希望它退出并顯示所需的錯誤訊息。
這是我非常簡單的代碼:
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
class Book {
public:
string title {};
string author {};
int pages {};
int readers {};
Book (string t, string a, int p)
: title{t}, author{a}, pages{p}, readers{0}
{
try{
if (pages <= 0)
throw invalid_argument ("Invalid page input");
}
catch (const invalid_argument& e){
cout << e.what() << endl;
exit; //Shoudn't it exit here?
}
}
void print()
{
cout << "Name: " << title << "\nAuthor: " << author
<< "\nPages: " << pages << "\nReaders: " << readers << endl;
}
};
int main()
{
Book book_1 ("Harry Potter", "JK Rowling", 0); //should exit here and give error?
book_1.print();
return 0;
}
當我第一次創建一個名為 book_1 的物件時,我認為程式應該退出。它甚至不應該進入列印它。為什么我的程式沒有退出?
我得到的輸出是:
Invalid page input
Name: Harry Potter
Author: JK Rowling
Pages: 0
Readers: 0
uj5u.com熱心網友回復:
嘗試exit(0)
或std::terminate()
代替exit;
您必須使用括號來呼叫該函式。沒有括號 exit 將只是一個未使用的數字,表示該函式的地址。
uj5u.com熱心網友回復:
catch 塊的目的是處理例外,以便它們(導致崩潰的例外)不會使您的程式崩潰并且可以正確處理。它的目的是處理崩潰的事情,而不是本身導致崩潰的事情。
uj5u.com熱心網友回復:
當我第一次創建一個名為 book_1 的物件時,我認為程式應該崩潰。
您的假設/理解不正確。在 C 中,我們可以通過拋出一個運算式來引發例外。此外,拋出的運算式的型別決定了將用于處理/處理該例外的處理程式。
此外,選定的處理程式將是:
a) 匹配拋出物件的型別,
b) 在呼叫鏈中是最近的。
這意味著控制元件從 throw(您“引發”例外的地方)傳遞到匹配的catch
.
為什么我的程式沒有崩潰?
將此應用于您的示例,我們看到您正在拋出一個型別的物件,std::invalid_argument
并且您有一個與拋出的物件的型別匹配的處理程式。因此,控制元件將傳遞給該處理程式,我們得到輸出Invalid page input
。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470839.html
下一篇:使用線性插值改變影像范圍