RapidXml throws an exception in case of an invalid XML file. Is it possible to recover from such a failure?
For example, is it possible to check if the XML is valid beforehand, or recover and continue on?
It seems that when such failures happen, there is only assert and exit of process, and no chance for recovery.
By default, RapidXML raises exceptions on parse errors; it doesn't assert (perhaps by assert you just meant the process aborts).
It is possible to configure RapidXML with your own error handler called rapidxml::parse_error_handler if you #define RAPIDXML_NO_EXCEPTIONS before including the RapidXML headers, and if such an error handler returns, RapidXML will call assert(0), but I suspect that you don't have that enabled and you just need to be catching the right exception.
There's just one exception to catch for parse errors, and it's called rapidxml::parse_error, but RapidXML will also throw std::runtime_error if it fails to find the file.
Here's an example which catches both exception types, plus some catch-all handlers:
#include <iostream>
#include "rapidxml.hpp"
#include "rapidxml_utils.hpp"
int main()
{
try
{
rapidxml::file<> xmlFile("test.xml");
rapidxml::xml_document<> doc;
doc.parse<0>(xmlFile.data());
}
catch (const std::runtime_error& e)
{
std::cerr << "Runtime error was: " << e.what() << std::endl;
}
catch (const rapidxml::parse_error& e)
{
std::cerr << "Parse error was: " << e.what() << std::endl;
}
catch (const std::exception& e)
{
std::cerr << "Error was: " << e.what() << std::endl;
}
catch (...)
{
std::cerr << "An unknown error occurred." << std::endl;
}
}
Related
I am using the following C++ code from the boost library :
try{
child c(commandString, (std_out & std_err) > pipe_stream);
} catch(process_error &pe){
cout<<pe.what()<<" second line"<<endl;
}
The commandString is a command like ls or any other command. But if a command that does not exist is typed as per the documentation it throws the process_error exception.
I am catching the exception here but not sure if there is a better way to print out the details of the exception or error than pe.what() above?
If you look at the boost reference about boost::process::process_error, you can read this:
struct process_error : public system_error {
};
It merely inherits std::system_error but can then be distinguished in the catch-block from other system errors.
emphasis mine
If you look then at the std::system_error reference, like all other standard exceptions, what() is the way to provide detailed information about the raised error so I would say yes, this is the proper way to print out the exception details.
But since boost::process::process_error does not override the what() function, it would return the same as a std::system_error would.
An alternative interface is using std::error_code.
There are pros and cons:
PRO: it enables you to get more detail about where an error condition arose. (This is a hypothetical difference because it's not specified whether what() may include info beyond an error condition)
CON: it might not get as much detail as in the exception message
CON: since some errors are exceptional, it's harder to express the possible error conditions in the interface: the error conditions get in the way in a way that exceptions do not
in your code you might have created this problem by handling exceptions: now how do decide what value(s) to return
NEUTRAL: you may still have to handle exceptions because exceptions can arise from any related code (e.g. during setup, doing allocations).
NEUTRAL: the code() member of boost::process::process_error is likely to be 100% identical to the error_code that you get
Demo
Contrast the implementations and output below:
Live On Coliru
#include <boost/process.hpp>
#include <iostream>
namespace bp = boost::process;
int using_exceptions(std::string const& commandString) {
try {
bp::pstream pipe_stream;
bp::child c(commandString, (bp::std_out & bp::std_err) > pipe_stream);
c.wait();
return c.exit_code();
} catch (std::exception const& e) {
std::cerr << "Exception: " << e.what() << std::endl;
return -1; // WHAT TO RETURN
}
}
int using_error_code(std::string const& commandString) {
try {
bp::pstream pipe_stream;
std::error_code ec;
bp::child c(commandString, (bp::std_out & bp::std_err) > pipe_stream,
ec);
if (ec) {
std::cerr << "Cannot spawn child process: " << ec.message() << "\n";
return -1; // WHAT TO RETURN?
} else {
c.wait(ec);
std::cerr << "Error: " << ec.message() << "\n";
return c.exit_code();
}
} catch (std::exception const& e) {
std::cerr << "Exception: " << e.what() << std::endl;
return -1; // WHAT TO RETURN
}
}
int main()
{
auto cmd = "/usr/bin/bogus";
std::cout << "Using error_code: " << using_error_code(cmd) << "\n";
std::cout << "Using exceptions: " << using_exceptions(cmd) << "\n";
}
Prints
Using error_code: Cannot spawn child process: No such file or directory
-1
Using exceptions: Exception: execve failed: No such file or directory
-1
I am writing a command-line application in C++. If an unhandled exception occurs, I don't want the app to crash badly, but to clean up as well as possible and print an error message.
How should I catch exceptions at the top-level in order to avoid the program crashing? Should I catch std::exception, ... or something else?
The quality of the cleaning you can do is a function of the exception being thrown.
For example, an exception that you raise yourself (perhaps derived from std::exception; let's call it fooexception) could well be handled quite elegantly.
So really you want a catch site on these lines
try {
/*whatever*/
} catch (fooexception& fe){
/*ToDo - handle my exception*/
} catch (std::exception& e){
/*ToDo - handle this generically*/
} catch (...){
/*Hum. That's bad. Let's do my best*/
}
Extend this at your leisure. Just remember that in a sense, multiple catch blocks behave like if else blocks: always order with the specific exceptions first.
Well, you could catch both:
int main() {
try {
// do stuff
}
catch(const std::exception& e) {
std::cout << "Caught exception: " << e.what() << std::endl;
}
catch(...) {
std::cout << "Caught unknown exception." << std::endl;
}
}
You should catch both, and possibly more. If you use a more specific exception type somewhere in the call stack, try to catch that as well.
Consider the code:
try
{
process();
}
catch (const SpecificException& ex)
{
std::cerr << "SpecificException occured: " << ex.what() << std::endl;
}
catch (const std::runtime_error& ex)
{
std::cerr << "std::runtime_error occured: " << ex.what() << std::endl;
}
catch (...)
{
std::cerr << "Unknown error occured!" << std::endl; // should never happen hopefully
}
And remember to always sort by specificness of exceptions - the more specialized/derived first, as the runtime will stop at the first catch block able to process the exception (i.e. first catch block with exception type matching or being a base of).
I would like to add information on what the program was about to do to my
exception handling. The old code had one big try-block around everything:
try {
read_cfg(); // a sub call might throw runtime_error
operation1();
operation2();
}
catch (std::exception& e) {
std::cerr
<< "Error: " << e.what() << ", "
// FIXME: also show what we were trying to do
// FIXME: and what a user could try
<< "\n";
}
Example error message:
Error: file "foo.cfg" not found, while reading configuration.
Please make sure the file exists.
I converted the try-block into three blocks, but this feels odd:
try {
read_cfg(); // a sub call might throw runtime_error
}
catch (std::exception& e) {
std::cerr
<< "Error: " << e.what() << ", "
<< "while reading configuration."
<< "\n";
}
try {
operation1();
}
catch (std::exception& e) {
std::cerr
<< "Error: " << e.what() << ", "
<< "while performing operation 1."
<< "\n";
}
try {
operation2();
}
catch (std::exception& e) {
std::cerr
<< "Error: " << e.what() << ", "
<< "while performing operation 2."
<< "\n";
}
I also tried to introduce one exception class per call (read_cfg_exception,
operation1_exception, operation2_exception). Since in read_cfg() the call to
open might throw, I catch its exception and convert it to a
read_cfg_exception, thereby saving the additional information, that something
whent wrong "while reading configuration". Yet this does not feel right either:
class read_cfg_exception;
void open(std::string name); // might throw std::runtime_error
void read_cfg()
{
try {
open("foo.cfg");
}
catch (std::runtime_error& e) {
throw read_cfg_exception(e.what() + "while reading configuration");
}
}
Therefor I have the question: What is a good pattern to show the additional
information of what the program was doing while the error occured.
take a look at POCO (c++ library) throwing system, that should answer all your questions, you'll learn a lot from that and many good style rules too. The answare to your question will be really long unfortunately (at least I don't know how to make it short).
Anyway don't implement something that makes your code not readable, in your example code is not readable and then not maintainable wich is not wanted.
Can i implement global exception handling in C++?
My requirement is try...catch block is not used in a piece of code then there should be a global exception handler which will handle all uncaught exception.
Can i achieve it, please give your valuable suggestion : )
I always wrap the outer-most function in a try-catch like this:
int main()
{
try {
// start your program/function
Program program; program.Run();
}
catch (std::exception& ex) {
std::cerr << ex.what() << std::endl;
}
catch (...) {
std::cerr << "Caught unknown exception." << std::endl;
}
}
This will catch everything. Good exception handling in C++ is not about writing try-catch all over, but to catch where you know how to handle it (like you seem to want to do). In this case the only thing to do is to write the error message to stderr so the user can act on it.
you can use a combination of set_terminate and current_exception()
i wanted to do the same, here's what i came up with
std::set_terminate([]() -> void {
std::cerr << "terminate called after throwing an instance of ";
try
{
std::rethrow_exception(std::current_exception());
}
catch (const std::exception &ex)
{
std::cerr << typeid(ex).name() << std::endl;
std::cerr << " what(): " << ex.what() << std::endl;
}
catch (...)
{
std::cerr << typeid(std::current_exception()).name() << std::endl;
std::cerr << " ...something, not an exception, dunno what." << std::endl;
}
std::cerr << "errno: " << errno << ": " << std::strerror(errno) << std::endl;
std::abort();
});
in addition to checking what(), it also checks ernno/std::strerror() - in the future i intend to add stack traces as well through exeinfo/backtrace() too
the catch(...) is in case someone threw something other than exception.. for example throw 1; (throw int :| )
In C++ the terminate function is called when an exception is uncaught. You can install your own terminate handler with the set_terminate function. The downside is that your terminate handler may never return; it must terminate your program with some operating system primitive. The default is just to call abort()
When an exception is raised, if is not caught at that point, it goes up the hierarchy until it is actually caught. If there is no code to handle the exception the program terminates.
You can run specific code before termination to do cleanup by using your own handlers of set_unexpected or set_terminate
Is there some way to catch exceptions which are otherwise unhandled (including those thrown outside the catch block)?
I'm not really concerned about all the normal cleanup stuff done with exceptions, just that I can catch it, write it to log/notify the user and exit the program, since the exceptions in these casese are generaly fatal, unrecoverable errors.
something like:
global_catch()
{
MessageBox(NULL,L"Fatal Error", L"A fatal error has occured. Sorry for any inconvience", MB_ICONERROR);
exit(-1);
}
global_catch(Exception *except)
{
MessageBox(NULL,L"Fatal Error", except->ToString(), MB_ICONERROR);
exit(-1);
}
This can be used to catch unexpected exceptions.
catch (...)
{
std::cout << "OMG! an unexpected exception has been caught" << std::endl;
}
Without a try catch block, I don't think you can catch exceptions, so structure your program so the exception thowing code is under the control of a try/catch.
Check out std::set_terminate()
Edit: Here's a full-fledged example with exception matching:
#include <iostream>
#include <exception>
#include <stdexcept>
struct FooException: std::runtime_error {
FooException(const std::string& what): std::runtime_error(what) {}
};
int main() {
std::set_terminate([]() {
try {
std::rethrow_exception(std::current_exception());
} catch (const FooException& e) {
std::cerr << "Unhandled FooException: " << e.what() << std::endl;
} catch (const std::exception& e) {
std::cerr << "Unhandled exception: " << e.what() << std::endl;
} catch (...) {
std::cerr << "Unhandled exception of unknown type" << std::endl;
}
std::abort();
});
throw FooException("Bad things have happened.");
// throw std::runtime_error("Bad things have happened.");
// throw 9001;
}
You can use SetUnhandledExceptionFilter on Windows, which will catch all unhandled SEH exceptions.
Generally this will be sufficient for all your problems as IIRC all the C++ exceptions are implemented as SEH.
Without any catch block, you won't catch any exceptions. You can have a catch(...) block in your main() (and its equivalent in each additional thread). In this catch block you can recover the exception details and you can do something about them, like logging and exit.
However, there are also downside about a general catch(...) block: the system finds that the exception has been handled by you, so it does not give any more help. On Unix/Linux, this help would constitute creating a CORE file, which you could load into the debugger and see the original location of the unexcepted exception. If you are handling it with catch(...) this information would be already lost.
On Windows, there are no CORE files, so I would suggest to have the catch(...) block. From that block, you would typically call a function to resurrect the actual exception:
std::string ResurrectException()
try {
throw;
} catch (const std::exception& e) {
return e.what();
} catch (your_custom_exception_type& e) {
return e.ToString();
} catch(...) {
return "Ünknown exception!";
}
}
int main() {
try {
// your code here
} catch(...) {
std::string message = ResurrectException();
std::cerr << "Fatal exception: " << message << "\n";
}
}
Update: This covers c++98 only.
From More Effective C++ by Meyers (pg 76), you could define a function that gets called when a function generates an exception that is not defined by its exception specification.
void convertUnexpected()
{
// You could redefine the exception here into a known exception
// throw UnexpectedException();
// ... or I suppose you could log an error and exit.
}
In your application register the function:
std::set_unexpected( convertUnexpected );
Your function convertUnexpected() will get called if a function generates an exception that is not defined by its exception specification... which means this only works if you are using exception specifications. ;(
Provided that C++11 is available, this approach may be used (see example from: http://en.cppreference.com/w/cpp/error/rethrow_exception):
#include <iostream>
#include <exception>
void onterminate() {
try {
auto unknown = std::current_exception();
if (unknown) {
std::rethrow_exception(unknown);
} else {
std::cerr << "normal termination" << std::endl;
}
} catch (const std::exception& e) { // for proper `std::` exceptions
std::cerr << "unexpected exception: " << e.what() << std::endl;
} catch (...) { // last resort for things like `throw 1;`
std::cerr << "unknown exception" << std::endl;
}
}
int main () {
std::set_terminate(onterminate); // set custom terminate handler
// code which may throw...
return 0;
}
This approach also allows you to customize console output for unhandled exceptions: to have something like this
unexpected exception: wrong input parameters
Aborted
instead of this:
terminate called after throwing an instance of 'std::logic_error'
what(): wrong input parameters
Aborted
This is what I always do in main()
int main()
{
try
{
// Do Work
}
catch(std::exception const& e)
{
Log(e.what());
// If you are feeling mad (not in main) you could rethrow!
}
catch(...)
{
Log("UNKNOWN EXCEPTION");
// If you are feeling mad (not in main) you could rethrow!
}
}
Use catch (...) in all of your exception barriers (not just the main thread). I suggest that you always rethrow (...) and redirect standard output/error to the log file, as you can't do meaningful RTTI on (...). OTOH, compiler like GCC will output a fairly detailed description about the unhandled exception: the type, the value of what() etc.