Fortran/error handling

Typically in an error situation, your program will stop, and you'll get an error message. The only exception to this is that at the end of  and   statements' parenthesized control list, you can add,   to determine which line to jump to in the event of an error.

Modern Fortran (from Fortran 90 onwards) has introduced four main areas for error capture:

1) File handling and i/o operation error handling

2) IEEE floating point error detection and reporting

3) Dynamic allocation

4) Command line operations

File handling and I/O Operations
All the external file handling statements and I/O operations (, ,  ,  ,  ,  ,  ,  ,   and  ) can now take optional   and   clauses. is an integer which returns a non-zero value if there is an error, in which case, the character variable assigned to  will return a brief error message. The non-zero integers and the messages are compiler dependent but the intrinsic module,, gives access to two important values:   and. If an error occurs, and  is non-zero, execution will not stop. The ERR clause is still supported but should not be used.

Example
Note that the length required for the message character is vendor and error dependent.

IEEE floating point error detection and reporting
This is a big topic, but in essence modern Fortran provides access to three intrinsic modules:,   and. These features can be used to intercept errors such as divide by zero and overflow but at the expense of some performance.

The  module controls access to the features the programmer may require, by use association in the scoping unit where the programmer places the use statement,

Example
See Chapter 11 in Metcalf et al, Modern Fortran Explained, OUP. All the necessary basic facilities exist in order for the programmer to construct a try/catch system if desired.

Dynamic Allocation
Modern Fortran allows run-time allocation and deallocation of arrays of any type, and a typical error might be to try to dynamically allocate an array so large that there is not enough memory, or an attempt to deallocate an array which is not already allocated. There are optional clauses  and   which can be used to prevent program failure and allow the programmer to take evasive action.

Example
These features are available in the equivalent coarray features.

Command Line Operations
Modern Fortran also supports error detection for the execution of command line operations,

Example
In this example, the programmer of the my.exe program has the responsibility for what codes are returned and what error messages are exposed, except that -1 and -2 are reserved for allowing the compiler vendor indicating what features may be supported.