Reputation: 40140
I have an old C based project, which I would like to port from an Atmel processor to Raspberry Pi.
At the time that it was written, C++ was not an option, and it would be too much effort, almost a rewrite, to convert it all to C++.
Some problems/crashes can't be (easily) caught by C, so sometimes my program will just die & I would like to send a last chance cry for help before expiring. No attempt at recovery and I can even live without details of the error, just so long as I get a message telling me to visit the equipment
Long story short, I think that I could have better error detection if I had exception handling.
I am thinking of using exception handling as chance of alerting me to go to the device and fetch the complete error log, reset the hardware etc. C won't always give me that last gasp chance to do something, if my code goes bang
Since I don't want to do a total C++ rewrite, would it be enough just to wrap main()
in try
/ catch
?
Is that technically enough, or do I need to do more?
Other than more detailed error reporting, is there anything to gain by wrapping every (major) function in it's own try
/ catch
?
Upvotes: 0
Views: 353
Reputation: 69854
Other than more detailed error reporting, is there anything to gain by wrapping every (major) function in it's own try / catch?
Firstly, only catch exceptions where you are in a position to alter the behaviour of the program in response to them (unless you're simply looking to add more contextual information via std::throw_with_nested()
)
Secondly, a c program will not exhibit RAII, so throwing exceptions in this circumstance is likely to leak resources unless you wrap all your handle and memory allocation in smart pointers or RAII-enabled handle classes.
You should do that before you consider adding exception handling.
If the program is likely to be actively maintained into the future, there is probably mileage in doing this. If not, probably better to leave sleeping dogs lie.
Upvotes: 1