3
I have a question regarding the treatment of exceptions in C++, the class Fracao below is purposely incomplete does not even possess setters or getters and several things have been "set aside", 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 launch of the exception within the constructor/method of the class, but also the treatment of the same, ie take out the blocks try and catch of int main, and treat it somewhere else avoiding that every time I need to create any object (like Fracao in that case) have to create it within a block try, followed by a catch.
#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;
}
Handle in which place?
– Maniero
@bigown Where would I normally be treated in a C++ program? My goal would be not to use Try catch for every object created on main.
– Luis Henrique
And then it would be dealt with where? It’s usually done where it needs to be done. If you want to do something different, you have to justify.
– Maniero
"does not even own setters or getters": javismo ? In C++, by Meno in my experience, classes have members that need to have, there is not much this concern with "setters" and "getters"
– zentrunix
@Joséx. It was just a way of saying that the class is simple, and to focus only on the problem, including thank you for your comment and agree with you.
– Luis Henrique