Fortran中是否存在异常处理?

Caf*_*ruz 11 error-handling fortran exception

Fortran中是否有任何异常处理结构,就像在Python中一样?

try:
    print "Hello World"
except:
    print "This is an error message!"
Run Code Online (Sandbox Code Playgroud)

如果它不存在,处理异常的最简单方法是什么?

Ale*_*ogt 12

Fortran中不存在异常,因此不存在异常处理.

但你可以使用标准Fortran做类似于异常处理的事情 - 甚至还有一篇关于它的文章Arjen Markus,"Fortran中的异常处理".

最常见的表示法是使用(整数)返回变量来指示错误代码:

subroutine do_something(stat)
    integer :: stat
    print "Hello World"
    stat = 0
end subroutine
Run Code Online (Sandbox Code Playgroud)

并在主程序中做

call do_something(stat)
if (stat /= 0) print *,"This is an error message!"
Run Code Online (Sandbox Code Playgroud)

本文中描述了其他方法,例如为能够存储错误消息的异常定义专用派生类型.最接近异常的那个例子是使用子例程的备用返回(但不能用函数):

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

    ! Some error occurred
    if (error) return 1
end subroutine
Run Code Online (Sandbox Code Playgroud)

并在主程序中做

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
Run Code Online (Sandbox Code Playgroud)

请注意,块结构需要符合Fortran 2008的编译器.

我从来没有见过这样的东西,但:)