Are exceptions used in the c++ part of FreeCAD?
When is it a good idea to use exceptions? When is it not?
What is the FreeCAD culture in what relates to throwing or not throwing exceptions?
Yes. We use and handle C++ exceptions. It’s probably a good idea to subclass yours from Base::Exception (or one of its subclasses). I suggest the C++ Core Guidelines as a good starting place for generic exception advice: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#S-errors
Do you have a specific case you are concerned about?
It would be nice to have a “thumbs up” here at the forum! ![]()
I am starting to write code, and I just wanted to follow the already established culture / guide lines.
I was a little concerned with python, but I saw that the generated code (using the xml) does catch every exception.
And, in general, I wanted to know “how far” I could throw one exception… ![]()
When writing code, I do not like to make assumptions that “everything is alright”. Even though things are not supposed to happen… I don’t know… some condition that (I think) is always supposed to be satisfied. For example, a sketch always has a vertical line. I tend to throw exceptions when things that should never happen do happen. Maybe, one day something changes and we start having those impossible stuff…
Those are exceptions that are not supposed to be thrown, so I do not keep catching them. It is like “trading a crash for an exception”. So… I hope some upper level will catch my exception and deal with it.
Please, don’t think I am an “exception freak”!!! I guess I only do this kind of stuff when I am not really sure if the situation is really impossible. When I have to deal with such a possibly impossible situation… I just throw… (I wanted to say “throw up”, because I expect some upper level will catch it).
A good rule to follow is to only catch an exception in code where you can do something sensible with the failed state. If your code doesn’t have any way of coping with the problem, then let someone above you handle it. In FreeCAD, a lot of times “handle” just means “report the failure to the user and bail out of the operation.”
There are some standard library calls that throw exceptions. For example std::m ap::at throws std::out_of_range.
Am I supposed to catch them and re-throw as Base::IndexError (or NameError), for example? Or can I simply leave it?
I would not hand-translate those. If you want to see what happens, just throw one on purpose.