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?
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 :)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With