Panic in Co-array Fortran

program main
  use iso_fortran_env, only: error_unit
  implicit none

  ! We'll use error termination throughout this site to check for
  ! unexpected errors. This is the only program on the
  ! site designed to terminate with an error.

  error stop "a problem"

  ! A common use of error termination is to abort if a function
  ! returns an error value that we don't know how to
  ! (or want to) handle. Here's an example of
  ! terminating if we get an unexpected error when creating a new file.

  integer :: unit
  integer :: iostat
  character(len=100) :: iomsg

  open(newunit=unit, file="/tmp/file", status="new", iostat=iostat, iomsg=iomsg)
  if (iostat /= 0) then
    write(error_unit,*) "Error creating file: ", trim(iomsg)
    error stop
  end if

end program main

Running this program will cause it to terminate with an error, print an error message, and exit with a non-zero status.

When the first error stop in main executes, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first error stop.

$ gfortran -o panic panic.f90
$ ./panic
ERROR STOP a problem

Note that unlike some languages which use exceptions for handling of many errors, in Fortran it is idiomatic to use error codes and status variables for error handling wherever possible.

In Fortran, there isn’t a direct equivalent to Go’s panic function. Instead, we use error stop to immediately terminate the program with an error message. This serves a similar purpose to panic in Go, allowing us to halt execution when an unexpected error occurs.

The open statement in Fortran is used to create or open files, similar to os.Create in Go. We use the iostat and iomsg specifiers to capture any errors that occur during the file operation.

Remember that Co-array Fortran is an extension of Fortran that adds parallel processing capabilities. In this example, we’re not using any Co-array specific features, but in more complex programs, you might use co-arrays for parallel execution across multiple images.