-3

Can I put just one all-encompassing try-catch statement in my main function that covers the entire program? Or do all functions require their own? What I mean is, will something like this work:

int main(){
    try{
        foo();
        bar();
    };

    catch(char* e){
        //Do stuff with e
    };
};

void foo(){throw "You'll never reach the bar.";};
void bar(){throw "Told you so.";};

If not, is there a similar way this can be done?

Kelvin Shadewing
  • 303
  • 2
  • 16

2 Answers2

2

Your example won't work because

  • Declaration of foo() and bar() are not before using them.
  • There is an extra semicolon between the block after try and catch.
  • What is passed to throw is const char*, but you catched only char*.

This example worked.

#include <iostream>

void foo();
void bar();

int main(){
    try{
        foo();
        bar();
    }

    catch(const char* e){
        //Do stuff with e
        std::cout << e << std::endl;
    }
}

void foo(){throw "You'll never reach the bar.";}
void bar(){throw "Told you so.";}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
1

Can I put just one all-encompassing try-catch statement in my main function that covers the entire program?

Yes. catch (...) catches everything.

#include <iostream>

int main()
{
    try
    {
        // do something
    }
    catch (...)
    {
        std::cerr << "exception caught\n";
    }
}

Or do all functions require their own?

No. That would defeat the whole purpose of exceptions.

catch(char* e){
    //Do stuff with e
};

This code is a result of the misunderstanding that exceptions are error messages. Exceptions are not error messages. Exceptions in C++ can be of any type. This includes char*, of course, but it is completely unidiomatic.

What you really want to do is catch std::exception, which includes an error message, accessible via the what() member function. Well-written C++ code only throws exceptions of type std::exception or derived classes. You can add ... as a fallback for all other cases:

 #include <iostream>
 #include <exception>

int main()
{
    try
    {
        // do something
    }
    catch (std::exception const& exc)
    {
        std::cerr << exc.what() << "\n";
    }
    catch (...)
    {
        std::cerr << "unknown exception caught\n";
    }
}
throw "You'll never reach the bar.";

Consequently, throwing char arrays is wrong. It's wrong on a technical level if you expect a char const[] to be converted to a char*, but it's especially wrong on a design level. Replace the array with a dedicated exception type like std::runtime_error:

throw std::runtime_error("You'll never reach the bar.");
Christian Hackl
  • 27,051
  • 3
  • 32
  • 62