whoami
whoami

Reputation: 1899

Why code inside catch does not get executed

I have a Foo class as follows

Foo.h

#pragma once
class Foo
{
public:
    Foo() = default;
    ~Foo() = default;

    void DoSomething();
};

Foo.cpp

#include "Foo.h"

void Foo::DoSomething()
{
    throw "something happened";
}

And I use the class like:

#include <iostream>
#include "Foo.h"

int main()
{
    try
    {
        Foo foo;
        foo.DoSomething();
    }
    catch (std::exception& e)
    {
        std::cout << e.what() << std::endl;
    }
}

I expect the code to go in the catch block. However, it never goes in there. What am I doing wrong here?

Upvotes: 1

Views: 112

Answers (1)

NathanOliver
NathanOliver

Reputation: 180630

When you do

throw "something happened"

You aren't throwing a std::exception. You are throwing a string literal which has a type of const char[N]. To catch it you would need a catch block like

catch (const char* e)
{
    std::cout << e << std::endl;
}

Alternatively you could throw something that derives from std::exception like a std::runtime_error and that would look like

void Foo::DoSomething()
{
    throw std::runtime_error("something happened");
}

...

catch (const std::exception& e) // catch by reference to const
{
    std::cout << e.what() << std::endl;
}

You can also specify a default handler like

catch (...)
{
    std::cout << "something bad happened - cannot recover" << std::endl;
}

which will catch any thrown exception but you wont be able to access whatever was thrown so you can only give a general message.

Upvotes: 10

Related Questions