Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does exception handling exist in Fortran?

Is there any exception handling structure in Fortran, just like in Python?

try:
    print "Hello World"
except:
    print "This is an error message!"

If it does not exist, what would be the easiest way to handle exceptions?

like image 835
Cafer Cruz Avatar asked Jan 11 '18 17:01

Cafer Cruz


2 Answers

Exceptions as such do not exist in Fortran, so no, there is no Exception handling.

But you can do something similar to Exception handling using Standard Fortran - there's even a paper on it Arjen Markus, "Exception handling in Fortran".

The most common notation is to use an (integer) return variable indicating the error code:

subroutine do_something(stat)
    integer :: stat
    print "Hello World"
    stat = 0
end subroutine

and in the main program do

call do_something(stat)
if (stat /= 0) print *,"This is an error message!"

There are other ways described in the paper such as defining a dedicated derived type for exceptions that is capable of also storing an error message. The example mentioned there that gets closest to an Exception is using alternate returns for subroutines (not possible with functions, though):

subroutine do_something(stat, *)
    integer :: stat
    !...

    ! Some error occurred
    if (error) return 1
end subroutine

and in the main program do

try: block
    call do_something(stat, *100)
    exit try ! Exit the try block in case of normal execution
100 continue ! Jump here in case of an error
    print *,"This is an error message!"
end block try

Please note that the block construct requires a compiler compliant with Fortran 2008.

I've never seen something like this out there, though :)

like image 129
Alexander Vogt Avatar answered Oct 20 '22 19:10

Alexander Vogt


There are proposals (see Steve Lionel's comment below) to add exception handling to the next Fortran standard. See here for example: Exception handling - BCS Fortran Specialist Group

This has apparently a long history in Fortran (again see Steve's second comment below)

like image 4
Scientist Avatar answered Oct 20 '22 17:10

Scientist