c++的异常机制

c++的异常机制
异常:一般是指打开文件失败,或者申请内存失败等一切不可预料的错误。

#include <iostream>

double Div(double, double);

int main(int argc, char * argv[])
{
        try //定义异常
        {
                std::cout << "7.3/2.0 = " << Div(7.3, 2.0) << std::endl;
                std::cout << "7.3/2.0 = " << Div(7.3, 0.0) << std::endl;
                std::cout << "7.3/2.0 = " << Div(7.3, 1.0) << std::endl;
        }
        catch(double) //捕获异常
        {
                std::cout << "eccept of deviding zero.\n";
        }
        std::cout << "That is ok.\n";
}

double Div(double a, double b)
{
        if (b == 0.0)
                throw b;//抛出异常
        return a/b;
}

wg@wg-laptop:/dos/test$ g++ 49.cc
wg@wg-laptop:/dos/test$ ./a.out
7.3/2.0 = 3.65
eccept of deviding zero.
That is ok.
 
  执行try模块里面的语句,到std::cout << "7.3/2.0 = " << Div(7.3, 0.0) << std::endl;这句时,因为b=0,后面std::cout << "7.3/2.0 = " << Div(7.3, 1.0) << std::endl;这句将不再执行,这个时候将抛出异常,而这个异常会被catch捕获。

本文出自 “cmdblock” 博客,谢绝转载!

你可能感兴趣的:(C++,职场,休闲)