0

I'm working in C++. I have a try...catch block, and the catch block catches runtime_error(error message). I want to do different things based on the different error messages. Here's some sample code:

#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;

int main()
{    
    string a = "hello";
    string b = "there";
    string c = "there";

    try{
        if(a == b){
            throw runtime_error("error 1");
        }
        if(b == c){
            throw runtime_error("error 2");
        }
    }
    catch(const runtime_error& error){
        cout << "error message: " << error.what();
        if(error.what() == "error 1"){
            // do thing a
        }
        else if(error.what() == "error 2"){
            // do thing b
        }
        else{
            // do thing c
        }
    }
}

The type of error.what() is not a string, though, (apparently it's PKc, whatever that means), and so I was looking for a way to do different things based on the error message in error.what(). Help

I tried error.what() == "error 1", which did not return true when error.what() was "error 1" apparently. Not entirely sure why, not sure what's going on here. I expected it to return true, but it doesn't.

  • 1
    Did you read the documentation for [`what()`](https://en.cppreference.com/w/cpp/error/exception/what)? It returns `const char*`, i.e., a C-style string. C-style strings are compared with [`strcmp`](https://en.cppreference.com/w/cpp/string/byte/strcmp). – Pete Becker Dec 06 '22 at 15:25
  • ahh... even though i saw that, didn't realize i had to use strcmp. Thanks!! – jettae schroff Dec 06 '22 at 17:05
  • You don't **have** to use `strcmp`, you can just create a temporary `std::string` on the fly and compare with it: `if (error.what() == std::string{ "error 1" }) { /* ... */ }`. Well, I see the linked duplicate already mentions other possibilities. – heap underrun Dec 06 '22 at 18:44

0 Answers0