How does Fortran stderr stop return code work?

2 minute read


  • stop returns integer on stderr by recommendation, since 1956 Fortran I
  • stop can also return constant character string since Fortran 77, no integer return with character
  • error stop in Fortran 2008: constant character with error code
  • error stop in Fortran 2018: variable character with error code, also allowed inside pure procedure.

Fortran 2018 finally brought the needed behavior for convenient error messages and continuous integration.

Since Fortran I in 1956, the stop statement has generally displayed a return code to indicate an error if an integer value was provided. Over time, stop statement behavior has changed to allow more refined signaling on program stop.

  • Since Fortran I 1956: stop without return code, just stop execution normally
  • Since Fortran I 1956: stop integer return code
    stop 1

    The Fortran 2008 and 2018 standards recommend that the error code be returned on iso_fortran_env: error_unit, which was first defined in Fortran 2003 standard. Earlier standards don’t say where the error code should go. Through Fortran 2018, stop with integer code is still normal program termination.

  • Since Fortran 77: stop may instead return a constant scalar character like “goodbye”. This generally sets stderr return code to 0, that is, no error is indicated.

For continuous integration, having a reliable way to indicate error behavior is crucial. For HPC, indicating abnormal conditions to the shell is also vital to avoid wasted resources on runs that suffered a computational error.

error stop

Fortran 2008 brought the long overdue error stop statement. stop still indicates normal program termination, and can for example stop individual images in a parallel executing program. Say an individual cell in a 3-D simulation did not find a stable solution. Depending on the simulation, that can be OK, perhaps set that value to NaN and stop with an error code on stderr, while letting the other images continue running.

However, in other types of simulations, an early failure to converge to a solution in a cell may invalidate the entire simulation taking a month of CPU time. Instead of writing cumbersome external checking code, the programmer can instead use error stop to reliably terminate all images when a critical failure is detected.

Fortran 2008: error stop with constant string or integer code (both return non-zero exit status on stderr)

Fortran 2018: error stop with variable scalar string or variable integer code. A vital addition of Fortran 2018 is that error stop can be used within pure procedures, a very commonly needed use case.

Fortran 2018 error stop variable character string allows for cleaner syntax, for example:

Fortran 2008:

use, intrinsic:: iso_fortran_env, only: stderr=>error_unit

write(stderr,*) 'the failure was in '//failedmod

error stop

Fortran 2018:

error stop 'the failure was in '//failedmod

Leave a Comment