MST

星途 面试题库

面试题:Fortran错误处理机制基础

在Fortran中,常见的错误处理语句有哪些?请举例说明如何使用`ON UNIT`语句来捕获文件操作中的错误。
19.4万 热度难度
编程语言Fortran

知识考点

AI 面试

面试题答案

一键面试

常见错误处理语句

  1. 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
    
  2. PAUSE:暂停程序执行,可用于调试。
    program pause_example
        integer :: i
        do i = 1, 10
            print *, '当前 i 的值:', i
            pause '暂停查看 i 的值'
        end do
    end program pause_example
    
  3. 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返回非零值,表明有错误发生,程序会跳转到错误处理标签处,打印错误信息并尝试关闭文件,同时处理关闭文件时可能发生的错误。