I am writing a program in Fortran 95 (to be compiled with with gfortran) containing a subroutine that performs a certain computation. As suggested in "Fortran 95/2003 for Scientists & Engineers" by S. J. Chapman, I am trying to stop the subroutine when an error is encountered and "throw"[1] an error flag that is "catch"ed[1] by the calling program, that will take all the necessary actions. Ideally, I am going for something like:
! Pseudo-code
PROGRAM my_prog
integer :: error_flag
CALL my_subr (<input_args>, <output_args>, error_flag)
! Also error_flag is an output: 0 -> everything OK, 1 -> error
IF (error_flag /= 0) THEN
WRITE (*,*) 'Error during execution of "my_subr"'
ELSE
... do something ...
END IF
END PROGRAM my_prog
如何停止子例程并优雅地处理错误?
这是一个例子:subroutine
“division”采用整数输入值,并迭代地将其除以输入值减去步骤数-1 的值。当该值达到零时,应提出标志并退出子例程而不执行除以零。
SUBROUTINE division (inval, outval, error_flag)
IMPLICIT NONE
INTEGER, INTENT(IN) :: inval
REAL, INTENT(OUT) :: outval
INTEGER, INTENT(OUT) :: error_flag ! 0 -> OK, 1 -> error
INTEGER :: i
REAL :: x
error_flag = 0
x = REAL(inval)
DO i = 0, 10
IF (inval-i == 0) error_flag = 1
! How can I gracefully exit now?
x = x / REAL(inval-i)
END DO
END SUBROUTINE division
PROGRAM my_prog
IMPLICIT NONE
REAL :: outval
INTEGER :: error_flag
CALL division (8, outval, error_flag)
IF (error_flag == 1) THEN
WRITE (*,*) 'Division by zero'
ELSE
WRITE (*,*) 'Output value:', outval
END IF
END PROGRAM my_prog
Notes:
[1] I am borrowing (in a probably inappropriate way) C++'s jargon.