I have a question regarding the handling of exceptions in C ++, the class Fracao
below is purposely incomplete does not even have setters or getters and several things were " left "side, has only two attributes and a constructor, and if the denominator receives zero, an exception will be thrown inside the constructor.
The code works perfectly, what I would like to know is if it is possible to do not only the throwing of the exception inside the constructor / class method, but also the handling of it, ie taking the blocks try
and% with catch
, and treat it elsewhere avoiding that every time I need to create any object (of type int main
in this case) has to create it inside a block Fracao
, followed by a try
.
#include <iostream>
#include <exception>
using namespace std;
class Fracao
{
private:
int numerador;
int denominador;
public:
Fracao(int numerador, int denominador);
};
Fracao::Fracao(int numerador, int denominador)
{
this->numerador = numerador;
if(denominador != 0)
this->denominador = denominador;
else
throw "Impossivel dividir por zero";
}
int main()
{
try
{
Fracao f1(1, 0);
}
catch(const char* msg)
{
cerr << "Erro: " << msg << endl;
}
catch(...)
{
cerr << "Erro desconhecido\n";
}
return 0;
}