Exceptions proposal

What I would prefer is a simple mechanism, that helps me in propagating an error condition upwards, basically by replacing a bunch of if (stat /= 0) return statements. And additionally, it should help me to enforce robust programming by making the error handling on the callers side mandatory (by either declaring that the error can be propagated further up or handling/catching it locally).

I don’t see, why it should add any big burden or run-time penalty for codes using it, if the error condition is an allocatable derived type containing an error code and maybe an optional error message. Being just an additional hidden allocatable, intent(out) dummy argument error, the code raising it would be equivalent to:

  ! raise error_type(code, msg)
  error = error_type(code, msg)   ! LHS is allocated with structure constructor
  return

On the caller side, if the error is not handled but propagated further up, it would be equivalent to

  call some_routine_which_throws_error(..., error)
  if (allocated(error)) return

And if the error is handled on the caller side, it would be equivalent to


  if (allocated(error)) then
    ! some statements handling the error

In the case of functions within expressions, it would be somewhat more complicated, but similar in the spirit.

For sure, in cases, where even an allocation is too much of an overhead, one can still use a simple integer as flag instead. And whenever it is possible to make robust routines carrying out their job without the need for an extra error signaling mechanism, one should certainly do so.

What I wish for is not much more than syntactic sugar, but would make my code (as demonstrated by @everythingfunctional above) more concise. I also do not expect much more from it. It does not have to deal with coarray-parallel issues, it is the callers responsibility IMO to synchronize the error handling and/or make sure that errors are raised/propagated upwards in a synchronized matter.

Note, that registering a callback function which is called at ERROR STOP is only limited use for library authors. (It gives the caller the possibility to make some finalization before everything is stopped / crashes, for sure, but maybe the caller wished to continue running nevertheless…)

There had been several demonstrations, that you can program something similar in pure Fortran already, as listed by @ivanpribec Fortran error handling including stacktrace generation - #2 by ivanpribec
But all of those solutions suffer from unnecessary verbosity due to boiler plate code. Having a concise syntax and the boiler plate being inserted by the compiler would be probably enough for many of us.

3 Likes