Search code examples
fortrangfortransubroutine

How to stop a subroutine and raise a flag?


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

How can I stop the subroutine and gracefully handle the errors?

Here is an example: the subroutine "division" takes an integer input value and iteratively divides it by a value that is the input value decremented by the number of steps-1. When such value reaches zero, a flag should be raised and the subroutine should be exited without performing the division by zero.

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.


Solution

  • Seeing your example it seems that you are just missing the return statement:

      error_flag = 0
      x = REAL(inval)
      DO i = 0, 10
         IF (inval-i == 0) then
                             error_flag = 1
                             return
         END IF
    
         x = x / REAL(inval-i)
      END DO