我正在尝试在我创建的目前没有错误检查的锻炼跟踪器程序中实现异常处理。我有一个Exlist
类来处理链接列表中的一系列函数,我希望在添加异常处理时使用一些重要的函数:
我如何从类中的函数抛出异常并在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 :(得分:2)
您应该创建一个继承自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;
}
抛出的异常会从你抛出的任何地方冒出来,直到它被抓住。如果它没有被捕获,程序将完成(可能没有展开堆栈(因此通常最好总是捕获main中的异常(强制堆栈展开),即使你重新抛出)。