exception - Fortran 中是否存在异常处理?

标签 exception error-handling fortran

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

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

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

最佳答案

Fortran 中不存在这样的异常,所以不,没有异常处理。

但是你可以使用标准 Fortran 做一些类似于异常处理的事情——甚至还有一篇关于它的论文 Arjen Markus, "Exception handling in Fortran" .

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

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

并在主程序中做
call do_something(stat)
if (stat /= 0) print *,"This is an error message!"

论文中还描述了其他方法,例如为异常定义专用的派生类型,该类型也能够存储错误消息。
那里提到的最接近 Exception 的示例是使用子例程的备用返回(尽管函数不可能):
subroutine do_something(stat, *)
    integer :: stat
    !...

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

并在主程序中做
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

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

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

关于exception - Fortran 中是否存在异常处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48212806/

相关文章:

java - 将自定义异常消息存储在文件或类中

java - 在方法体内抛出异常并在之后捕获它

javascript - 处理 JavaScript 错误

c - ret2libc segfault地址为0x0000000000000000

c# - 如何跨 SOAP Web 服务传播异常?

mysql - 让SQL抛出错误然后完全处理或防止错误?

windows - 如何处理失败的 `system` 调用?

C++ 类函数调用 fortran 子例程

parameters - 在 Fortran 子例程中从输入变量定义参数

带有子例程和函数的 Fortran OpenMP