簡體   English   中英

如何在 c++ 中捕獲異常?

[英]How do you catch an exception in c++?

我一直在嘗試 output “隊列已滿”,這是在我的其他代碼中聲明的。 我怎么抓住這個?

這是我的主要

int main() {
    IntQueue iQueue(5);
    try {
        cout << "Enqueuing 5 items...\n";
        // Enqueue 5 items.
        for (int x = 0; x < 5; x++)
            iQueue.enqueue(x);
    } catch (...) {
        // Attempt to enqueue a 6th item.
        cout << "Now attempting to enqueue again...\n";
        iQueue.enqueue(5);
    }

這是我的其他代碼

if (isFull())
    throw std::runtime_error("Queue is full");
else {
    cout << "Enqueueing: " << num << endl;
    // Calculate the new rear position
    rear = (rear + 1) % queueSize;
    // Insert new item
    queueArray[rear] = num;
    // Update item count
    numItems++;
}

catch塊下的任何代碼都旨在捕獲try塊中拋出的任何異常,這意味着您應該編寫任何可能在其中拋出異常的代碼:

try {
    // trying to enqueue 6 items, which is above limit.
    for (int x = 0; x < 6; x++) { 
        iQueue.enqueue(x);
    }
} catch (exception e) { 
    cout << e.what() << '\n';
}

以下是捕獲異常並打印其消息的方法:

try {
   // ...
} catch (std::runtime_error const& e) {
   std::cout << e.what() << '\n'; // or std::cerr, std::perror, or smth else
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM