Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching fortran runtime errors and signals in C++ binding

I would like to be able to catch a terminating Fortran runtime errors in a C++ binding. I have a legacy F90 code to bind to and expect all kind of errors e.g. numerical, IO etc.

I managed to handle STOP according to: Intercepting Fortran STOP from C++ and able to throw/catch exception for this case in the C++ code.

I got some understanding 'Signal Handling in Fortran' at https://www.sharcnet.ca/help/images/4/42/Fortran_Signal_Handling.pdf

However I do not manage with this, an example for f90 fortran would be very helpful.

For example trying to open a non existant file in the fortran subroutine would give a runtime error, and the C++ code terminates:

open (unit=13,FILE="fnameBAD",status="old",action="read",position="rewind")

Fortran runtime error: Cannot open file 'fnameBAD': No such file or directory

I would like to be able to catch this and other runtime errors using signals.

like image 386
levego70 Avatar asked Oct 27 '25 05:10

levego70


1 Answers

This won't work, at least for GFortran. When then OPEN statement fails, the GFortran runtime library will shut itself down, and only finally is the signal generated. So by the time you can catch the signal in the signal handler, libgfortran has already shut itself down (including closing all open files).

The solution, as Vladimir F says in a comment, is to catch the error in the OPEN statement with the iostat= specifier.

like image 143
janneb Avatar answered Oct 29 '25 18:10

janneb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!