`

C++巩固与知新----异常处理

    博客分类:
  • C++
 
阅读更多

异常处理

1.throw表达式:错误检测部分使用这种表达式来说明遇到了不可处理的错误,可以说throw引发了异常条件。

2.Try块:以try开始,以一个或者多个catch结束,对于try块中处理的代码抛出的异常,catch会进行处理。

基本结构:

try
{
//程序中抛出异常
throw value;
}
catch(valuetype v)
{
//例外处理程序段
}<!--EndFragment-->

基本解释如下:

try包含你要防护的代码 ,称为防护块防护块如果出现异常,会自动生成异常对象并抛出.

catch捕捉特定的异常,并在其中进行适当处理.

throw可以直接抛出/产生异常,导致控制流程转到catch.

说明:

(1)trycatch块中必须要用花括号括起来,即使花括号内只有一个语句也不能省略花括号;(2)trycatch必须成对出现,一个try_catch结果中只能有一个try块,但可以有多个catch块,以便与不同的异常信息匹配;(3)如果在catch块中没有指定异常信息的类型,而用删节号"...",则表示它可以捕获任何类型的异常信息;(4)如果throw不包括任何表达式,表示它把当前正在处理的异常信息再次抛出,传给其上一层的catch来处理;(5)C++中一旦抛出一个异常,如果程序没有任何的捕获,那么系统将会自动调用一个系统函数terminate,由它调用abort终止程序;

说明部分转自:http://www.cnblogs.com/CaiNiaoZJ/archive/2011/08/19/2145349.html

 

其实,也可以自定义exception或者unexception

具体可以参考http://blog.csdn.net/makenothing/article/details/43273137

 

最后上一段代码,一个经典的例子展示异常处理的重要性:

代码1:

<!--EndFragment-->

#include<iostream>
using namespace std;
double fuc(int x, int y)                        //定义函数
{
 if (y == 0)
 {
  throw y;                                    //除数为0,抛出异常int
 }
 return x / y;                                    //否则返回两个数的商
}
void main()
{
 int res,a;
 while (true)
 {
  cin >> a;
  try                                            //定义异常
  {

   res = fuc(2, a);
   cout << "The result of x/y is : " << res << endl;
  }
  catch (int)                                    //捕获并处理异常
  {
   cerr << "error of dividing zero.\n";
   system("pause");
   exit(1);                                    //异常退出程序
  }
  }
}

输入:0

输出:error of dividing zero.

代码2:自定义exception、unexpection、terminate

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

//自定义exception类
class Myexception : public exception
{
public:
 const char* what() const throw()
 {
  return "error!";
 }
};
void myUnexpected()
{
 cout << "Unexpected exception caught!\n";
 system("pause");
 exit(-1);
}
void myTerminate() //##1 set it be the terminate handler   
{
 cout << "Unhandler exception!\n";
 system("pause");
 exit(-1);
}
//将异常抛出封装在一个函数里。若后面接throw(...)则...代表允许抛出的异常类型,
//若无则表示不允许抛出异常,系统进入unexpection

//若后面什么都没有,则表示可以接受任何的异常处理
void check(int x){
 if (x == 0)
 {
  throw Myexception();
 }
}
int main()
{
 unexpected_handler oldHandler = set_unexpected(myUnexpected);
 terminate_handler preHandler = set_terminate(myTerminate);
 int x = 100, y = 0;
 try
 {
  check(y);
  cout << x / y;
 }
 catch (Myexception &e) //no catch sentence matches the throw type   
 {
  cout << e.what << endl;
 }
 catch (...)
 {
 //处理未知的异常
  cout << "unknown error!" << endl;
 }
 system("pause");
 return 0;
}

结果自然是error!

<!--EndFragment--><!--EndFragment-->
1
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics