My habits were formed before Fortran introduced ERROR STOP, but reading What is the difference between STOP and ERROR STOP?, I see it’s what I should be using to handle errors.
For functions I think the two main approaches are ERROR STOP or returning an obviously bad RESULT, that one hopes the calling program will catch, for example
pure function correl(x,y) result(corr)
! use ERROR STOP
real, intent(in) :: x(:),y(:)
real :: corr
if (size(x) < 2) then
error stop "in correl, need size(x) > 1"
else if (size(x) /= size(y)) then
error stop "in correl, need size(x) == size(y)"
end if
! calculate corr
end function correl
!
function correl_old(x,y) result(corr)
! use STOP if compiler does not support error stop
real, intent(in) :: x(:),y(:)
real :: corr
if (size(x) < 2) then
print*,"in correl, need size(x) > 1"
stop
else if (size(x) /= size(y)) then
print*,"in correl, need size(x) == size(y)"
stop
end if
! calculate corr
end function correl_old
!
pure function correl_f95(x,y) result(corr)
! return clearly bad result for invalid input
real, intent(in) :: x(:),y(:)
real :: corr
if (size(x) < 2) then
corr = -2.0
return
else if (size(x) /= size(y)) then
corr = -3.0
return
end if
! calculate corr
end function correl_f95