Chinaunix首页 | 论坛 | 博客
  • 博客访问: 360745
  • 博文数量: 100
  • 博客积分: 2500
  • 博客等级: 大尉
  • 技术积分: 1209
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-15 21:24
文章分类

全部博文(100)

文章存档

2011年(100)

分类: C/C++

2011-04-19 13:33:55

To catch exceptions we must place a portion of code under exception inspection. This is done by enclosing that portion of code in a try block. When an exceptional circumstance arises within that block, an exception is thrown that transfers the control to the exception handler. If no exception is thrown, the code continues normally and all handlers are ignored.

Example:
  1. #include <iostream>
  2. using namespace std;

  3. int
  4. main(void)
  5. {
  6.         try {
  7.                 throw 20;
  8.         } catch (int e) {
  9.                 cout << "An exception occurred." << e << endl;
  10.         }

  11.         return (0);
  12. }
If this throw specifier is left empty with no type, this means the function is not allowed to throw exceptions. Functions with no throw specifier (regular functions) are allowed to throw exceptions with any type。

  1. #include <iostream>
  2. #include <exception>
  3. using namespace std;

  4. class myexception: public exception {
  5.         virtual const char *what() const throw()
  6.         {
  7.                 return "My exception happened";
  8.         }
  9. }myex;

  10. int
  11. main(void)
  12. {
  13.         try
  14.         {
  15.                 throw myex;
  16.         }
  17.         catch (exception &e)
  18.         {
  19.                 cout << e.what() << endl;
  20.         }

  21.         return (0);
  22. }
The C++ Standard library provides a base class specifically designed to declare objects to be thrown as exceptions. It is called exception and is defined in the header file under the namespace std. This class has the usual default and copy constructors, operators and destructors, plus an additional virtual member function called what that returns a null-terminated character sequence (char *) and that can be overwritten in derived classes to contain some sort of description of the exception.

All exceptions thrown by components of the C++ Standard library throw exceptions derived from this std::exception class.




阅读(878) | 评论(0) | 转发(0) |
0

上一篇:名字空间

下一篇:类型转换

给主人留下些什么吧!~~