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?
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.");