简体   繁体   English

如何在C ++异常处理中包装我的C代码?

[英]How to wrap my C code in C++ exception handling?

I have an old C based project, which I would like to port from an Atmel processor to Raspberry Pi. 我有一个基于C的旧项目,我想从Atmel处理器移植到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++. 在编写它时,C ++并不是一种选择,要将其全部转换为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. C不能(轻松)抓住某些问题/崩溃,所以有时我的程序会死掉,而我想在到期前发出最后一次求助的机会。 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 我正在考虑使用异常处理作为提醒我进入设备并获取完整错误日志,重置硬件等的机会。如果我的代码无法正常运行,C不会总是给我最后的喘息机会

Since I don't want to do a total C++ rewrite, would it be enough just to wrap main() in try / catch ? 由于我不想完全重写C ++,仅将main()包装在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 ? 除了更详细的错误报告之外,通过将每个(主要)函数包装在自己的try / catch是否有任何收获?

Other than more detailed error reporting, is there anything to gain by wrapping every (major) function in it's own try / catch? 除了更详细的错误报告之外,通过将每个(主要)函数包装在自己的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() ) 首先,仅捕获可以更改程序行为以响应它们的异常(除非您只是想通过std::throw_with_nested()添加更多上下文信息)

Secondly, ac 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. 其次,ac程序不会显示RAII,因此在这种情况下引发异常可能会泄漏资源,除非您将所有句柄和内存分配包装在智能指针或启用了RAII的句柄类中。

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. 如果没有的话,最好留下熟睡的狗撒谎。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM