您的位置:首页 > 编程语言 > C语言/C++

C++基础编程----5.1try和异常处理

2015-10-29 16:51 162 查看

            try和异常处理

 异常是存在于运行时的反常行为,这些行为超出了函数的正常功能。

 当程序的某部分检测到一个它无法处理的问题时,需要异常处理。

 throw   try  catch子句

1. throw表达式

        throw表达式引发一个异常,表达式的类型就是抛出异常的类型。

 if(item1.isbn()==item2.isbn())

  throw runtime_error("Data must refer to same ISBN");

 cout<<item1+item2<<endl;

        类型runtime_error是一种标准库异常类型的一种,定义在stdexcept头文件中。

2.try语句块

 try语句块的通用语法形式:

 try{

  program-statements;

 }

 catch(exception-declaration)

 { handler-statements}

 catch(exception-declaration)

 { handler-statements}

 catch(...)      //  避免其他没有考虑到的异常情况

 { handler-statements}

3.编写处理代码

 while(cin>>item1>>item2)

 {

  try{

   if(item1.isbn()==item2.isbn())

    throw runtime_error("Data must refer to same ISBN");

   cout<<item1+item2<<endl;

  }

  throw(runtime_error err)

  {

   cout<<err.what()<<endl;           //  输出对象信息       每个标准库异常类都定义了名为what的成员函数,返回值为const char*类型

  }

 }

4.标准异常

 exception头文件定义了最通用的异常类exception类

 stdexcept头文件定义了如下的异常类:

  runtime_error类

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  trycatch异常处理