第十八章 18.1.2节练习

来源:互联网 发布:爱宝v6软件 编辑:程序博客网 时间:2024/05/20 10:15

练习18.4

查看图18.1(第693页)所示的继承体系,说明下面的try块有何错误并修改它。

try{  // 使用C++标准库} catch(exception) {  // ...} catch (const runtime_error &re) { // ...} catch (overflow_error eobj) { /* ... */ }

解答:

【引用】当程序使用具有继承关系的多个异常时必须对catch语句的顺序进行组织和管理,使得派生类异常的处理代码出现再基类异常的处理代码之前。

18.4.cc: In function ‘int main()’:18.4.cc:11:3: warning: exception of type ‘std::runtime_error’ will be caught } catch (const runtime_error &re) {   ^18.4.cc:9:3: warning:    by earlier handler for ‘std::exception’ } catch(exception) {   ^18.4.cc:13:3: warning: exception of type ‘std::overflow_error’ will be caught } catch (overflow_error eobj) { /* ... */ }   ^18.4.cc:11:3: warning:    by earlier handler for ‘std::runtime_error’ } catch (const runtime_error &re) {   ^
gcc 4.9.1会给这段代码一些警告。


try{    // 使用C++标准库} catch (overflow_error eobj) {  /* ... */}catch (const runtime_error &re) {   // ...}catch(exception) {    // ...}

改成这样就不会有警告了。同样的,这样的修改依据的是693页的继承关系图。


练习18.5

修改下面的main函数,使其能捕获图18.1(第693页)所示的任何异常类型:

int main(){

  // 使用C++标准库

}

处理代码应该首先打印异常相关的错误信息,然后调用abort(定义再cstdlib头文件中)终止main函数。

解答:

#include <iostream>#include <cstdlib>#include <stdexcept>using namespace std;int main(){  try{    range_error r("error");    throw r;  } catch(...) {    cerr << "exception here!!" << endl;    abort();  }}
因为使用catch(...)所以对与异常的类型是未知的,所以无法使用相关函数打印出对应的信息。

当然,这里可以重新抛出,然后对类型进行确定,再进行打印。


练习18.6

已知下面的异常类型和catch语句,书写一个throw表达式使其创建的异常对象能被这些 catch语句捕获:

(a) class exceptionType {};

      catch(exceptionType *pet) {}

(b) catch(...)

(c) typedef int EXCPTYPE;

      catch(EXCPTYPE) {}

解答:

(a)

  try{    exceptionType *e;    throw e;  } catch(exceptionType *pet) {    cerr << "exception here!!" << endl;  }

(b)

这个就参考上一题的代码吧。

(c)

  try{    throw EXCPTYPE();  } catch(EXCPTYPE) {    cerr << "exception here!!" << endl;  }

0 0
原创粉丝点击