2012-12-12 55 views
0

我试图在我创建的锻炼跟踪程序中实现异常处理,目前没有错误检查。我有一个Exlist类来处理一个链表一系列的功能,一些重要的功能,我想在加的异常处理:捕捉类功能引发的异常

  • 更新列表到文本文件
  • 排序列表按日期
  • 编辑锻炼(搜索列表使用键)用键删除
  • 删除锻炼(搜索列表)
  • 添加锻炼

^h我会去抛出一个类中的函数的异常,并在int main()中捕获它们。我知道简单的异常处理在同一个块中,但我似乎无法想出一个解决方案来解决这个问题。我的理想情况是:

//in int main, when the user selects add 
try 
{ 
    WorkoutList.addEx(); 
} 
//other code... 
//catch at end of loop and display error 
catch(string error) 
{ 
    cout << "Error in: addEx..." << error << endl; 
} 
+0

是否有任何不工作用你提交的代码? –

+3

不要抛出'std :: string'对象!你应该只抛出派生自std :: exception'的类的对象,尽管你可以抛出任何可复制的类,但捕获随机类使得它更难确定发生了什么。捕捉'std :: exception const&'并查看'what()'成员是否至少给出了一些提示。 –

+0

这正是例外情况!只需将它们扔到任何地方'冒泡'直到它们被抓住,破坏掉那些超出范围的物体 – Roddy

回答

1

您应该创建一个从Exception继承的异常类。例如,如果你想扔掉它时,增加了一个错误的值,你可以这样做:

#include <stdexcept> 
class WrongValueException : public std::runtime_error 
{ 
    public: 
     WrongValueException(string mess): std::runtime_error(mess) {} 
}; 

然后,在addEx()功能,把它

//SomeCode 
if(value.isWrong()){ 
    throw WrongValueException("Wrong Value"); 
} else { 
    //add 
} 

,赶上它在主:

int main(){ 
    //SomeCode 
    try 
    { 
     WorkoutList.addEx(); 
    } 
    //other code... 
    //catch at end of loop and display error 
    catch(WrongValueException const& ex) 
    { 
     std::cerr << "WrongValueException: " << ex.what() << std::endl; 
    } 
    catch(std::exception const& ex) 
    { 
     std::cerr << "std::exception: " << ex.what() << std::endl; 
     throw; 
    } 
    catch(...) 
    { 
     std::cerr << "Unknown Exception: " << ex.what() << std::endl; 
     throw; 
    } 

抛出的异常将从您抛出的任何位置起泡,直到它被捕获。如果它没有被捕获,程序将结束(可能没有展开堆栈(因此,即使你重新抛出也总是捕获主要异常(强制堆栈展开),最好是最好的。)

+0

修正了错误。 :-) –