Review Error Handling

Review Error Handling

0. General Rules
    -We should pay more attention on assert usage and make it a part of the error/exception handling mechanism.
    -Attention: 异常是first-class的语言机制。代码分析工具可以识别出异常并进行各种监测或分析。比如PerfMon就会对程序中的异常做统计.


1. SEH (Structured Exception Handling)
    - Its concept. Structured exception handling is a mechanism for handling both hardware and software exceptions.        
    - For .Net platform, SEH is enabled by default; while for native c++, you can explicitly control whether to use it or not by project setting -> C/C++ -> Code Generation -> Enable C++ Exception.
    - See below example:
    (C#)
    try
    {
        int b = 0;
        int a = 3 / b;
    }
    catch (Exception e)
    {
        Console.WriteLine(e); // touch here.
    }
    (C++)
    try
    {
        int b = 0;
        int a =  2 / b;
    }
    catch(...)            // if SEH is disabled, as the app can't catch it, crash!
    {
        printf("exception caught due to divided by zero!\n"); // If SEH is enabled, touch here.
    }
2. Try Catch Performance Issue
    (C++ Coding Standards)实际上,现代的编译器早已能够做到异常在happy path上的零开销。当然,空间开销还是有的,因为零开销方案用的是地址表方案;但相较于时间开销,这里的空间开销几乎从来都不是个问题。   另一方面,一旦发生了异常,程序肯定就出了问题,这个时候的时间开销往往就不那么重要了。

3. RAII (Resource acquisition is Initialization)
    -- For C++, it's done by initalizing resource allocation in constructor and releasing them in destructor.
    -- For C#, it's done by letting a class implement IDispose and using "scope Using" to enable automatic IDispose calling when exiting that code block.
    -- For C#/Jave, try--catch--finally is another way to make sure resource release.

你可能感兴趣的:(error)