【问题标题】:How do you catch an exception in c++?如何在 C++ 中捕获异常?
【发布时间】:2021-05-23 19:01:54
【问题描述】:

我一直在尝试输出在我的其他代码中声明的“队列已满”。我如何捕捉到这个?

这是我的主线

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++;
}

【问题讨论】:

  • iQueue.enqueue(5); 在 catch 块中抛出另一个异常?

标签: c++ exception methods queue try-catch


【解决方案1】:

以下是捕获异常并打印其消息的方法:

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

【讨论】:

    【解决方案2】:

    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';
    }
    

    【讨论】:

      猜你喜欢
      • 2011-01-26
      • 1970-01-01
      • 2011-07-02
      • 2020-11-23
      • 1970-01-01
      • 2011-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多