所以我有一个即将到来的任务来处理异常并在我当前的通讯簿程序中使用它们,大部分作业都围绕着它。我决定尝试处理异常和整个 try catch 的事情,并使用类设计,这是我在几周内最终必须为我的作业做的事情。我有工作代码可以很好地检查异常,但我想知道的是,是否有办法标准化我的错误消息函数(即我的 what() 调用):
这是我的代码:
#include <iostream>
#include <exception>
using namespace std;
class testException: public exception
{
public:
virtual const char* what() const throw() // my call to the std exception class function (doesn't nessasarily have to be virtual).
{
return "You can't divide by zero! Error code number 0, restarting the calculator..."; // my error message
}
void noZero();
}myex; //<-this is just a lazy way to create an object
int main()
{
void noZero();
int a, b;
cout << endl;
cout << "Enter a number to be divided " << endl;
cout << endl;
cin >> a;
cout << endl;
cout << "You entered " << a << " , Now give me a number to divide by " << endl;
cin >> b;
try
{
myex.noZero(b); // trys my exception from my class to see if there is an issue
}
catch(testException &te) // if the error is true, then this calls up the eror message and restarts the progrm from the start.
{
cout << te.what() << endl;
return main();
}
cout <<endl;
cout << "The two numbers divided are " << (a / b) << endl; // if no errors are found, then the calculation is performed and the program exits.
return 0;
}
void testException::noZero(int &b) //my function that tests what I want to check
{
if(b == 0 ) throw myex; // only need to see if the problem exists, if it does, I throw my exception object, if it doesn't I just move onto the regular code.
}
我想做的就是让我的 what() 函数可以根据调用的错误类型返回一个值。因此,例如,如果我调用一个看起来是顶部数字 (a) 的错误,以查看它是否为零,如果是,它会将消息设置为“你不能拥有一个零分子”,但仍然在 what() 函数中。这是一个例子:
virtual const char* what() const throw()
if(myex == 1)
{
return "You can't have a 0 for the numerator! Error code # 1 "
}
else
return "You can't divide by zero! Error code number 0, restarting the calculator..."; // my error message
}
这显然行不通,但是有没有办法做到这一点,所以我不会为每个错误消息编写不同的函数?