Fortran Error Handling
Fortran has no exceptions. Errors are handled in two ways: statements that can fail (allocation, I/O, type conversion) return a status code that you check, and procedures that detect a problem either return an error flag to their caller or stop the program with error stop.
Status codes: stat=, iostat=, errmsg=, iomsg=
Without a status argument, a failing allocate, open or read terminates the program with a runtime message. With one, the statement returns a code and the program continues, so you can decide what to do:
| Statement | Status | Message |
|---|---|---|
allocate, deallocate |
stat=ierr |
errmsg=msg |
open, read, write, close, inquire |
iostat=ios |
iomsg=msg |
Zero always means success. For I/O, a negative value means end of file (iostat_end) or end of record (iostat_eor), and a positive value means an error.
program io_errors
implicit none
integer :: u, ios
character(len=200) :: msg
open(newunit=u, file='does_not_exist.csv', status='old', action='read', &
iostat=ios, iomsg=msg)
if (ios /= 0) then
print '(a)', 'Could not open the input file:'
print '(2x, a)', trim(msg)
end if
end program io_errorsCould not open the input file:
Cannot open file 'does_not_exist.csv': No such file or directory
Validating input
A classic task: parse numbers from text and report bad entries instead of crashing.
program parse_values
implicit none
character(len=8) :: fields(5) = [character(len=8) :: '12.5', '7', 'abc', '-3e2', '4,2']
real :: value, total
integer :: i, ios, good
total = 0.0
good = 0
do i = 1, size(fields)
read(fields(i), *, iostat=ios) value
if (ios /= 0) then
print '(3a)', 'skipping invalid entry "', trim(fields(i)), '"'
cycle
end if
total = total + value
good = good + 1
end do
print '(a, i0, a, f8.2)', 'parsed ', good, ' values, total = ', total
end program parse_valuesskipping invalid entry "abc"
parsed 4 values, total = -276.50
Careful: '4,2' was not rejected. List-directed input treats the comma as a separator, so it read 4 and ignored the rest. If an entry must be exactly one number, read it with an explicit format such as '(f8.0)', or check that nothing follows the number.
Returning error flags from procedures
Library-style procedures shouldn't stop the program: the caller may know how to recover. The usual Fortran convention is an optional integer stat (and maybe a message) as the last arguments:
module safe_math
use iso_fortran_env, only: real64
implicit none
integer, parameter :: dp = real64
integer, parameter :: ERR_NONE = 0, ERR_DOMAIN = 1
contains
subroutine safe_sqrt(x, root, stat, errmsg)
real(dp), intent(in) :: x
real(dp), intent(out) :: root
integer, intent(out) :: stat
character(len=:), allocatable, intent(out), optional :: errmsg
root = 0.0_dp
if (x < 0.0_dp) then
stat = ERR_DOMAIN
if (present(errmsg)) errmsg = 'safe_sqrt: negative argument'
return
end if
stat = ERR_NONE
root = sqrt(x)
end subroutine safe_sqrt
end module safe_math
program use_safe_math
use safe_math
implicit none
real(dp) :: inputs(3) = [16.0_dp, -4.0_dp, 2.0_dp], r
integer :: i, stat
character(len=:), allocatable :: msg
do i = 1, size(inputs)
call safe_sqrt(inputs(i), r, stat, msg)
if (stat == ERR_NONE) then
print '(a, f6.2, a, f10.6)', 'sqrt(', inputs(i), ') = ', r
else
print '(a, i0, a, a)', 'error ', stat, ': ', msg
end if
end do
end program use_safe_mathsqrt( 16.00) = 4.000000
error 1: safe_sqrt: negative argument
sqrt( 2.00) = 1.414214
Stopping the program: stop and error stop
stopends the program normally. It can print a message or return an exit code:stop 'finished',stop 0.error stopends the program abnormally, with a non-zero exit status so that shell scripts,makeand batch systems notice the failure. In a parallel program it stops all images.
Messages from both go to standard error.
program stopping
implicit none
real :: dt = -0.01
print '(a)', 'checking configuration...'
if (dt <= 0.0) error stop 'time step dt must be positive'
print '(a)', 'never reached'
end program stoppingRunning it prints the message and exits with status 1. gfortran also prints a backtrace (memory addresses that differ from run to run, which is why this example isn't runnable here):
checking configuration...
ERROR STOP time step dt must be positive
Error termination. Backtrace:
#0 0x... in ???
...Since Fortran 2018 the stop code may be a variable expression, and error stop can be given an integer code that becomes the exit status: error stop 3.
Runtime checks while developing
Many errors in Fortran are not detected at all by default: an array index out of bounds, using an unallocated array, or an integer overflow silently produce garbage. Compile with checks while developing and testing:
gfortran -g -Wall -Wextra -fcheck=all -fbacktrace -ffpe-trap=invalid,zero,overflow prog.f90-fcheck=all: array bounds, unallocated arrays, pointer and argument checks;-fbacktrace: shows where a crash happened;-ffpe-trap=...: stop at the first floating-point exception (NaN, division by zero, overflow) instead of silently propagating it.
For floating-point exceptions at run time, the standard modules ieee_arithmetic and ieee_exceptions let you test values (ieee_is_nan(x)) and query flags:
program nan_check
use, intrinsic :: ieee_arithmetic, only: ieee_is_nan, ieee_is_finite, &
ieee_value, ieee_quiet_nan
implicit none
real :: values(4)
integer :: i
values = [1.0, ieee_value(1.0, ieee_quiet_nan), huge(1.0), 0.0]
values(3) = values(3) * 10.0 ! overflows to +Infinity
do i = 1, 4
print '(a, i0, a, l1, a, l1)', 'value ', i, ': nan=', ieee_is_nan(values(i)), &
' finite=', ieee_is_finite(values(i))
end do
end program nan_checkvalue 1: nan=F finite=T
value 2: nan=T finite=F
value 3: nan=F finite=F
value 4: nan=F finite=T
Test yourself
What happens when read(line, *) x fails and no iostat= is given?
- x is set to zero
- The program terminates with a runtime error
- The statement is skipped silently
- x becomes NaN
What does a negative iostat value mean?
- An error
- Success
- End of file (or end of record)
- A warning
What is the difference between stop and error stop?
- None
error stopsignals abnormal termination with a non-zero exit statusstoponly works in subroutineserror stoprestarts the program