HP Fortran Programmer's Guide (March 2010)

Using the ON statement
Actions specified by ON
Chapter 5138
Trapping floating-point exceptions
The following program, call_fptrap.f90, causes an invalid operation exception and includes
an ON statement to handle the exception. The ON statement calls the trap procedure
trap_illegal, which assigns a different value to the result argument. The program prints
the result. Here is the program listing:
Example 5-3 call_fptrap.f90
PROGRAM main
REAL :: x, y
ON REAL ILLEGAL CALL trap_illegal
x = -10.0
y = LOG(x) ! causes an invalid operation
PRINT *, y
END PROGRAM main
SUBROUTINE trap_illegal(res)
! res is the result value of the invalid operation
! trapped by the ON statement
REAL :: res
res = 99.87 ! assign another value to the result argument
END SUBROUTINE trap_illegal
Here is the command line, followed by the output from a sample run:
$ f90 call_fptrap.f90
$ a.out
99.87
Upon exit from a trap procedure, control returns to the instruction following the one that
activated the trap, regardless of whether the erring instruction appears in user code or in a
library routine.
Without the ON statement, this program would never execute its trap procedure and output a
NaN, as shown by the output from a similar program in “Ignoring errors” on page 136.
Trapping integer overflow exceptions
This section discusses an example program that illustrates how to use the ON statement to call
a trap procedure for an integer overflow exception.
An integer overflow occurs when an operation on an integer variable results in the attempt to
assign it an out-of-range value. HP Fortran does not trap this exception by default. However,
you can use the ON statement in conjunction with the $HP$ CHECK_OVERFLOW directive to trap
an integer overflow. The following program, call_itrap.f90, illustrates how to do this: