C++之父Bjarne Stroustrup提供的关于异常处理的建议

    节选自《The C++ Programming Language》 ——C++之父Bjarne Stroustrup 
         1. Don’t use exceptions where more local control structures will suffice;    当局部的控制能够处理时,不要使用异常; 
         2. Use the "resource allocation is initialization" technique to manage resources;   使用“资源分配即初始化”技术去管理资源; 
         3. Minimize the use of try-blocks. Use "resource acquisition is initialization" instead of explicit handler code;    尽量少用try-catch语句块,而是使用“资源分配即初始化”技术。 
         4. Throw an exception to indicate failure in a constructor;     如果构造函数内发生错误,通过抛出异常来指明。 
         5. Avoid throwing exceptions from destructors;     避免在析构函数中抛出异常。 
         6. Keep ordinary code and error-handling code separate;      保持普通程序代码和异常处理代码分开。 
         7. Beware of memory leaks caused by memory allocated by new not being released in case of an exception;  小心通过new分配的内存在发生异常时,可能造成内存泄露。 
         8. Assume that every exception that can be thrown by a function will be thrown;    如果一个函数可能抛出某种异常,那么我们调用它时,就要假定它一定会抛出该异常,即要进行处理。 
         9. Don't assume that every exception is derived from class exception;     要记住,不是所有的异常都继承自exception类。 
         10. A library shouldn't unilaterally terminate a program. Instead, throw an exception and let a caller decide;    编写的供别人调用的程序库,不应该结束程序,而应该通过抛出异常,让调用者决定如何处理(因为调用者必须要处理抛出的异常)。 
         11. Develop an error-handling strategy early in a design;    若开发一个项目,那么在设计阶段就要确定“错误处理的策略”。  

 

posted @ 2016-09-22 15:11  LonelyEnvoy  阅读(216)  评论(0编辑  收藏  举报