The program also attempts to divide by zero. Although the ONstatement enables the trap triggered by a divide-by-zero exception, the statement has no other effect. As a result, the exception will cause the program to abort. To ignore the divide-by-zero exception would require an additional ONstatement:

ON REAL DIV 0 IGNORE

Here is command line to compile the program, followed by the output from a sample run:

$ f90 ignore.f90 $ a.out

NaN

PROGRAM ABORTED : IEEE divide by zero

PROCEDURE TRACEBACK:

(0)0x00002504 _start + 0xbc [./a.out]

Calling a trap procedure

You can write trap procedures that are callable by the ON statement to handle arithmetic errors in user code and in library routines. Trap procedures can take zero or one argument. If an argument is specified, it is the result and must have the type specified by the exception keyword. For example, if the following ONstatement occurs in a program:

ON DOUBLE PRECISION OVERFLOW CALL trap

then the procedure trap could declare one argument of type DOUBLE PRECISION. Note that the argument is optional. Also, depending on the exception, the contents of the argument may not always be meaningful.

The following sections discuss two example programs that use the ONstatement to call a trap procedure for floating-point exception and for an integer exception.

Trapping floating-point exceptions

The following program, call_fptrap.f90, causes an invalid operation exception and includes an ONstatement to handle the exception. The ONstatement 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 16 Example5-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 *, yEND 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

Trapping integer overflow exceptions

This section discusses an example program that illustrates how to use the ONstatement 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. HPFortran does not trap this exception by default. However, you can use the ON statement in conjunction with the $HP$ CHECK_OVERFLOWdirective to trap an integer overflow. The following program, call_itrap.f90, illustrates how to do this:

84 Using the ON statement

Page 84
Image 84
HP UX Fortran Software Calling a trap procedure, Trapping floating-point exceptions, Trapping integer overflow exceptions