Jak tworzyć wyjątki?

Mam więc nadchodzące zadanie, które zajmuje się wyjątkami i używam ich w moim aktualnym programie książki adresowej, na którym koncentruje się większość zadań domowych. Zdecydowałem się pobawić wyjątkami i całą próbą złapania i użyć projektu klasy, co w końcu będę musiał zrobić dla mojego zadania w ciągu kilku tygodni. Mam działający kod, który sprawdza, czy wyjątek jest w porządku, ale chcę wiedzieć, czy istnieje sposób na ujednolicenie mojej funkcji komunikatu o błędzie (tj. Mojego wywołania what ()):

Oto mój kod:

#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.
  }

Chciałbym móc to zrobić, aby moja funkcja what () mogła zwrócić wartość zależną od rodzaju wywoływanego błędu. Na przykład, gdybym wywołał błąd, który wyglądał na najwyższy numer, (a), aby sprawdzić, czy jest to zero, a jeśli tak, to ustawiłby komunikat, że „nie można mieć licznik zera ”, ale nadal znajduje się wewnątrz funkcji what (). Oto przykład:

  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
  }

To oczywiście nie zadziałałoby, ale czy istnieje sposób, aby to zrobić, więc nie piszę innej funkcji dla każdego komunikatu o błędzie?

questionAnswers(4)

yourAnswerToTheQuestion