Error Handling
Fortran has no exceptions.
Fortran has no exceptions. Errors are handled with status arguments and checks.
integer :: stat, ios
character(len=256) :: errmsg
allocate(a(n), stat=stat, errmsg=errmsg)
if (stat /= 0) then
write(error_unit, *) "Allocation failed: ", trim(errmsg)
error stop 1
end if
open(newunit=u, file=fname, status="old", iostat=ios, iomsg=errmsg)
if (ios /= 0) then
write(error_unit, '(a)') "Cannot open "//trim(fname)//": "//trim(errmsg)
return
end if
read(line, *, iostat=ios) value
if (ios /= 0) print *, "Invalid number: ", trim(line)20.1 Error-handling patterns
Return an error code (integer, intent(out) :: ierr) or a logical ok flag from subroutines.
Provide optional stat/errmsg arguments mirroring intrinsic conventions; stop if they're absent.
Use error stop for unrecoverable situations; stop for normal termination.
Validate inputs at module boundaries.
Libraries: stdlib_error (check, error_stop), ferror, error-handling derived types.
subroutine safe_sqrt(x, y, ierr)
real, intent(in) :: x
real, intent(out) :: y
integer, intent(out), optional :: ierr
if (x < 0.0) then
if (present(ierr)) then
ierr = 1; y = 0.0; return
else
error stop "safe_sqrt: negative argument"
end if
end if
y = sqrt(x)
if (present(ierr)) ierr = 0
end subroutine safe_sqrt20.2 Runtime checking
Compile with checks during development: gfortran -fcheck=all -g -fbacktrace -ffpe-trap=invalid,zero,overflow (bounds, uninitialized pointers, array conformance, floating-point exceptions).