Error Handling Patterns
Guarded Divide
Return a Status
A guard checks the risky condition before doing the work. The caller can inspect a status value and keep control flow explicit.
Program
Play the program to choose a divisor and watch the guard choose a result and status.
guarded_divide.f90
program guarded_divide_demo
implicit none
integer :: numerator, divisor
integer :: quotient, status
numerator = 20
divisor =
if (divisor == 0) then
quotient = 0
status = 1
else
quotient = numerator / divisor
status = 0
end if
print '(I0, 1X, I0)', quotient, status
end program guarded_divide_demo
program guarded_divide_demo
implicit none
integer :: numerator, divisor
integer :: quotient, status
numerator = 20
divisor =
if (divisor == 0) then
quotient = 0
status = 1
else
quotient = numerator / divisor
status = 0
end if
print '(I0, 1X, I0)', quotient, status
end program guarded_divide_demo
program guarded_divide_demo
implicit none
integer :: numerator, divisor
integer :: quotient, status
numerator = 20
divisor =
if (divisor == 0) then
quotient = 0
status = 1
else
quotient = numerator / divisor
status = 0
end if
print '(I0, 1X, I0)', quotient, status
end program guarded_divide_demo
guard
The `if` condition checks for the unsafe divisor before division.
status
`status = 1` records the failure path without stopping the program.
normal path
When the guard is false, the program computes the quotient normally.