nomad icon indicating copy to clipboard operation
nomad copied to clipboard

Exceptions may be thrown from C interface functions

Open paulapatience opened this issue 1 year ago • 4 comments

It is undefined behavior to throw exceptions from functions marked extern "C". Yet, createNomadProblem does just this. Probably it should use new(std::nothrow) instead of plain new when creating the NomadProblemInfo, exiting early if the allocation fails, and also catch std::bad_alloc when creating the shared pointer. solveNomadProblem also creates a shared pointer without catching std::bad_alloc.

I have not looked at the NOMAD::AllParameters methods to see if they may throw as well. If they may, then exceptions must be similarly caught.

paulapatience avatar Feb 19 '24 13:02 paulapatience

@paulapatience They may. It is the user's responsibility to be careful about the parameter arguments he gives to the function. For the exception that can be thrown on new, could you make a PR (on the development branch)?

salomonl avatar Feb 19 '24 18:02 salomonl

It is the user's responsibility to be careful about the parameter arguments he gives to the function.

The problem with that stance is that in interactive languages such as Python and Julia — in other words, in many of the non-C interfaces of NOMAD — providing invalid arguments to functions is not undefined behavior. Python, and Julia I think, just throw exceptions, and users expect that.

If the C interface does not catch C++ exceptions before they leak across the extern "C" boundary, there is no telling what may occur if a user of PyNomad provides invalid arguments. It could crash the whole REPL process or application, which is inconvenient, or blithely continue running, which is worse.

I will make a PR, or two, depending on the complexity, for catching memory allocation and other exceptions which the C++ code may throw. Either today or tomorrow.

paulapatience avatar Feb 20 '24 19:02 paulapatience

For PyNomad, when a user provides an invalid parameter by default we have the following:

python simpleExample_basis_tmp.py

Unknown parameter: TOTO

BBE OBJ

1 1.0243

If an exception occurs during the bb evaluation. Usually we want to continue the optimization. Nomad supports/accepts evaluation failures of blackbox. The user can have a try/except like what is done in examples/advanced/library/PyNomad/simpleExample_PbWithConst.py

ctribes avatar Feb 21 '24 15:02 ctribes

For PyNomad, when a user provides an invalid parameter by default we have the following:

Ah, I had not realized that PyNomad wraps the C++ interface. The rest of my comments apply, however. Any user of the C interface will have problems if C++ exceptions leak through. For example by calls to the addNomad*Param functions.

paulapatience avatar Feb 21 '24 21:02 paulapatience