Panic in Fortran

program panic_example
    use, intrinsic :: iso_fortran_env, only: error_unit
    implicit none

    ! A 'stop' statement in Fortran is similar to panic in other languages.
    ! It typically means something went unexpectedly wrong. Mostly we use it 
    ! to fail fast on errors that shouldn't occur during normal operation, 
    ! or that we aren't prepared to handle gracefully.

    ! We'll use stop throughout this site to check for unexpected errors. 
    ! This is the only program on the site designed to stop abruptly.
    stop "a problem"

    ! A common use of stop 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 
    ! stopping if we get an unexpected error when opening 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 opening file: ", trim(iomsg)
        stop
    end if

end program panic_example

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

When the first stop statement is executed, 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 stop statement.

$ gfortran panic_example.f90 -o panic_example
$ ./panic_example
STOP a problem

Note that unlike some languages which use exceptions for handling of many errors, in Fortran it is idiomatic to use error-indicating return values (like iostat) wherever possible.

In Fortran, there isn’t a direct equivalent to Go’s panic and recover mechanism. The stop statement is used for abrupt program termination, but it doesn’t provide the same level of control as Go’s panic. For more controlled error handling, Fortran programmers typically use status codes, error flags, or custom error handling routines.