Home > front end >  Program doesn't crash after try catch block and thrown exception
Program doesn't crash after try catch block and thrown exception

Time:05-09

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

CodePudding user response:

The catch block's purpose is to handle exceptions so they (exceptions that cause crashes) don't crash your program and can be handled properly. It's purpose is to handle things that crash and not itself cause a crash.

CodePudding user response:

I thought the program should crash when I first created an object named book_1.

Your assumption/understanding is incorrect. In C , we can raise an exception by throwing an expression. Moreover, the type of the thrown expression determines the handler that will be used to deal/handle with that exception.

Additionally, the selected handler will be the one that:

a) matches the type of the thrown object,

b) is nearest in the call chain.

This means that the control is passed from the throw(where you "raised" the exception) to the matching catch.


Why is my program not crashing?

Applying this to your example, we see that you're throwing an an object of type std::invalid_argument and you've a handler that matches the type of the thrown object. Hence the control will be passed to that handler and we get the output Invalid page input.

  • Related