程序在尝试捕获块并引发异常后不会崩溃

  • 本文关键字:异常 崩溃 程序 c++ try-catch
  • 更新时间 :
  • 英文 :


今天,当我的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

尝试exit(0)std::terminate()而不是exit;,您必须使用括号来调用函数。加上out括号,exit将只是一个未使用的数字,表示该函数的地址。

当我第一次创建一个名为book_1的对象时,我认为程序应该崩溃。

你的假设/理解是不正确的。在c++中,可以引发抛出表达式引起的异常。而且,抛出表达式的类型决定了处理程序将用于处理该异常。

另外,所选择的处理程序将是:

a)匹配被抛出对象的类型,

b)在呼叫链中最近。

这意味着控件是从抛出(您在其中"引发")传递的。(例外)到匹配catch


为什么我的程序没有崩溃?

将此应用到您的示例中,我们看到您正在抛出类型为std::invalid_argument的对象,并且您有一个与所抛出对象的类型匹配的处理程序。因此,控件将传递给该处理程序,我们得到输出Invalid page input

最新更新