Today I was very surprised when my try catch block didn't work as I inticipated. I expected it to exit with a desired error message when an error in my try block was found.
This is my very simple code:
#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;
}
I thought the program should exit when I first created an object named book_1. It shoudn't even go into printing it. Why is my program not exiting?
The ouput I'm getting is:
Invalid page input
Name: Harry Potter
Author: JK Rowling
Pages: 0
Readers: 0