C++ Primer 读书笔记 - 第六章

这一章讲控制结构,和C,Java没区别。

跟C不同的是,C++增加了try blocks and Exception Handling

#include <iostream>
#include <stdexcept>
using namespace std;

void foo()
{
    int b = 0;
    if (b == 0)
        throw runtime_error("b == 0");
    int a = 4/b;
    cout << a << endl;
}

void bar() throw(int)
{
    throw 5;
}

int main()
{
    try {
        //foo(); 
        bar();
    } catch (runtime_error err){
        cout << err.what() << endl;
    } catch (int i) {
        cout << "int: " << i << endl;
    } catch (...) {
        cout << "default" <<endl;
    }
    return 0;
}

调试时使用预处理

g++ -D NDEBUG test.cpp
#include <iostream>
using namespace std;

int main()
{
    #ifndef NDEBUG
    cerr << "starting main" << endl;
    #endif
    string a = "abcdefg";
    int threshold  = 10;
    if (a.size() < threshold)
        cerr << "Error: " << __FILE__
             << " : line " << __LINE__ << endl
             << "       Complied on " << __DATE__
             << " at " << __TIME__ << endl
             << "       Word read was \"" << a
             << "\" Length too short" << endl;
    return 0;
}

 

posted on 2013-05-25 03:59  NULL00  阅读(436)  评论(0编辑  收藏  举报

导航