Recover in Co-array Fortran

program recover_example
  use iso_fortran_env, only: error_unit
  implicit none

  call main()

contains

  subroutine may_panic()
    error stop "a problem"
  end subroutine may_panic

  subroutine main()
    integer :: error_status
    character(len=100) :: error_message

    call execute_command_line("./may_panic", exitstat=error_status, &
                              cmdstat=error_status, cmdmsg=error_message)

    if (error_status /= 0) then
      write(error_unit,*) "Recovered. Error:"
      write(error_unit,*) trim(error_message)
    end if

    print *, "After may_panic()"
  end subroutine main

end program recover_example

Co-array Fortran doesn’t have built-in panic and recover mechanisms like some other languages. However, we can simulate similar behavior using error handling and external command execution.

In this example, we define two subroutines:

  1. may_panic(): This subroutine simulates a panic by using error stop with an error message.

  2. main(): This is our main subroutine where we handle the potential error.

The main() subroutine uses execute_command_line to run may_panic() as an external command. This allows us to catch any errors that occur during its execution.

If an error occurs (i.e., error_status /= 0), we print a “Recovered” message along with the error details. This simulates the recovery process.

The line print *, "After may_panic()" will always be executed in this case, unlike in some other languages where code after a panic might not run. This is because we’re using external command execution to simulate the panic and recover behavior.

To run this program:

  1. Save the may_panic subroutine as a separate executable.
  2. Compile and run the main program:
$ gfortran -o recover_example recover_example.f90
$ ./recover_example
Recovered. Error:
 a problem
After may_panic()

This approach doesn’t provide the same level of control as languages with built-in panic and recover mechanisms, but it demonstrates a way to handle and recover from errors in Co-array Fortran.