Catching std::strings and c-style strings at once

Discussion in 'C++' started by Kurt Krueckeberg, Nov 17, 2004.

  1. "Ney André de Mello Zunino" <> wrote in message
    news:...
    > Hello.
    >
    > Given the following try...catch construct:
    >
    > try
    > {
    > }
    > catch (const string& msg)
    > {
    > }
    >
    > I might be overlooking something basic, but why can't the compiler use one
    > of std::string's constructors in order to match:
    >
    > throw "Something happened!";
    >
    > The intent is to avoid having to add an extra catch block, i.e.:
    >
    > try
    > {
    > }
    > catch (const string& msg)
    > {
    > }
    > catch (const char* const msg)
    > {
    > }
    >
    > Thank you,


    It is a bad practice to throw literals. It leads to code like
    catch(const char *text) {
    string str(text);
    if (text == "error1") //...
    else if (text == "error2") //...
    else if (text == "error3")//...

    }
    Kurt Krueckeberg, Nov 17, 2004
    #1
    1. Advertising

  2. "Ney André de Mello Zunino" <> wrote...
    > Given the following try...catch construct:
    >
    > try
    > {
    > }
    > catch (const string& msg)
    > {
    > }
    >
    > I might be overlooking something basic, but why can't the compiler use one
    > of std::string's constructors in order to match:
    >
    > throw "Something happened!";
    >
    > The intent is to avoid having to add an extra catch block, i.e.:
    >
    > try
    > {
    > }
    > catch (const string& msg)
    > {
    > }
    > catch (const char* const msg)
    > {
    > }


    Matching between the type of the object thrown and the handler
    is done in such way that user-defined conversions are not allowed.

    class A {
    public:
    A(int);
    };

    int main() {
    try {
    throw 5;
    }
    catch (A) {
    }
    }

    should produce "unhandled exception".

    V
    Victor Bazarov, Nov 17, 2004
    #2
    1. Advertising

  3. Hello.

    Given the following try...catch construct:

    try
    {
    }
    catch (const string& msg)
    {
    }

    I might be overlooking something basic, but why can't the compiler use
    one of std::string's constructors in order to match:

    throw "Something happened!";

    The intent is to avoid having to add an extra catch block, i.e.:

    try
    {
    }
    catch (const string& msg)
    {
    }
    catch (const char* const msg)
    {
    }

    Thank you,

    --
    Ney André de Mello Zunino
    =?ISO-8859-1?Q?Ney_Andr=E9_de_Mello_Zunino?=, Nov 17, 2004
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.

Share This Page