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/