c++异常简单实例

来源:互联网 发布:智能化网络综合布线 编辑:程序博客网 时间:2024/04/30 03:39

   c++支持异常,与异常相关的关键字有:try,catch,throw。其实异常类的实现并不神秘,本文将通过一个简单的例子说明如何实现一个简单的异常类,还是先看下面一个简单的异常实现代码:

  #include <iostream>
#include <string>
using namespace std;
class Exception
{
 public:
 Exception(string s)
 {
  cout<<"exception"<<s<<endl;
 }
 ~Exception()
 {
 }
}
f()
{
 int x;
 cin>>x;
 if(!x)
 {
  throw(Exception("test"));
 }
 else
 {
  cout<<"x is not 0"<<endl;
 }
}
int main()
{
 try
 {
  f();
 }
 catch(Exception e)
 {
  cout<<"catch an exception"<<endl;
 }
}

程序功能是接受一个数字,如果是0的话旧抛出异常。

原创粉丝点击