面试题答案
一键面试常见错误处理语句
ERROR STOP
:用于立即终止程序执行,并输出错误信息。program error_example real :: a a = 1.0 / 0.0 ! 这会导致除零错误 if (a > 100.0) then error stop '计算结果超出预期范围' end if end program error_example
PAUSE
:暂停程序执行,可用于调试。program pause_example integer :: i do i = 1, 10 print *, '当前 i 的值:', i pause '暂停查看 i 的值' end do end program pause_example
STOP
:终止程序执行,不过与ERROR STOP
不同,它一般用于正常结束或无特定错误信息的结束。program stop_example integer :: num num = 5 if (num == 5) then stop '程序正常结束' end if end program stop_example
使用ON UNIT
语句捕获文件操作中的错误
ON UNIT
语句用于在指定设备(如文件)上发生错误时,跳转到指定的语句标签处执行。
program on_unit_example
integer :: unit_num = 10
integer :: ierr
open(unit = unit_num, file = 'nonexistent_file.txt', status = 'old', iostat = ierr)
on unit(unit_num) ierr, error_label
if (ierr /= 0) then
print *, '文件打开错误'
else
print *, '文件成功打开'
close(unit = unit_num)
end if
stop
error_label:
print *, '捕获到文件操作错误,错误号:', ierr
close(unit = unit_num, iostat = ierr)
if (ierr /= 0) then
print *, '关闭文件时也发生错误,错误号:', ierr
end if
end program on_unit_example
在上述代码中,尝试打开一个不存在的文件。ON UNIT
语句指定如果在设备unit_num
(即文件)上发生错误,跳转到error_label
标签处执行。如果打开文件时iostat
返回非零值,表明有错误发生,程序会跳转到错误处理标签处,打印错误信息并尝试关闭文件,同时处理关闭文件时可能发生的错误。