c++异常处理

通过异常处理,可以将问题的检测和问题的解决分离,这样程序的问题检测部分可以不必了解如何处理问题。

由问题检测部分抛出一个异常对象给问题处理代码,通过这个对象的类型和内容,两个部分能够就出现了什么错误进行通信。

Sales_item operator+(const Sales_item& lhs, const Sales_item& rhs)
{
  if (!lhs.same_isbn(rhs))
throw runtime_error(“Data must refer to same ISBN”);
  // ok, if we’re still here the ISBNs are the same to it’s okay to do the addition
  Sales_item ret(lhs); 
  ret += rhs;
  return ret;
}

在程序的其他部分,将Sales_item对象相加的那部分代码放到一个try块中,以便异常发生时捕获异常。

// part of the application that interacts with the user
Sales_item item1, item2, sum;
while (cin >> item1 >> item2) 
{
  try
  {
sum = item1 + item2; // calculate their sum
// use sum
  }
  catch (const runtime_error &e)
  {
cerr << e.what() << “ Try again. \n” << endl;
  }
}

 

posted on 2012-12-20 12:00  zhuyf87  阅读(254)  评论(0编辑  收藏  举报

导航