码迷,mamicode.com
首页 > 编程语言 > 详细

C++异常

时间:2016-04-14 13:51:23      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

1.异常号是有try块中抛出

// exceptions
#include <iostream>
using namespace std;

int main () {
  try
  {
    throw 20;
  }
  catch (int e)      //e = 20
  {
    cout << "An exception occurred. Exception Nr. " << e << \n;
  }
  return 0;
}
try {
  // code here
}
catch (int param) { cout << "int exception"; }
catch (char param) { cout << "char exception"; }
catch (...) { cout << "default exception"; }

 

 

2.标准异常

#include <iostream>
#include <exception>
using namespace std;

class myexception: public exception
{
  virtual const char* what() const throw()
  {
    return "My exception happened";
  }
} myex;

int main () {
  try
  {
    throw myex;
  }
  catch (exception& e)    //标准异常
  {
    cout << e.what() << \n;
  }
  return 0;
}

#include <iostream>
#include <exception>
using namespace std;

int main () {
  try
  {
    int* myarray= new int[1000];    //内存分配失败
  }
  catch (exception& e)
  {
    cout << "Standard exception: " << e.what() << endl;
  }
  return 0;
}

 

 

 

C++异常

标签:

原文地址:http://www.cnblogs.com/hinice/p/5390632.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!