|
1 | 1 | module stdlib_experimental_error
|
| 2 | +use, intrinsic :: iso_fortran_env, only: stderr=>error_unit |
2 | 3 | implicit none
|
3 | 4 | private
|
4 | 5 | public :: assert, error_stop
|
5 | 6 |
|
6 | 7 | contains
|
7 | 8 |
|
8 |
| -subroutine assert(condition) |
| 9 | +subroutine assert(condition, code) |
9 | 10 | ! If condition == .false., it aborts the program.
|
10 | 11 | !
|
11 | 12 | ! Arguments
|
12 | 13 | ! ---------
|
13 | 14 | !
|
14 | 15 | logical, intent(in) :: condition
|
| 16 | +integer, intent(in), optional :: code |
15 | 17 | !
|
16 | 18 | ! Example
|
17 | 19 | ! -------
|
18 | 20 | !
|
19 | 21 | ! call assert(a == 5)
|
20 | 22 |
|
21 |
| -if (.not. condition) call error_stop("Assert failed.") |
| 23 | +if (.not. condition) call error_stop("Assert failed.", code) |
22 | 24 | end subroutine
|
23 | 25 |
|
24 |
| -subroutine error_stop(msg) |
| 26 | +subroutine error_stop(msg, code) |
25 | 27 | ! Aborts the program with nonzero exit code
|
26 | 28 | !
|
27 |
| -! The statement "stop msg" will return 0 exit code when compiled using |
28 |
| -! gfortran. error_stop() uses the statement "stop 1" which returns an exit code |
29 |
| -! 1 and a print statement to print the message. |
| 29 | +! The "stop <character>" statement generally has return code 0. |
| 30 | +! To allow non-zero return code termination with character message, |
| 31 | +! error_stop() uses the statement "error stop", which by default |
| 32 | +! has exit code 1 and prints the message to stderr. |
| 33 | +! An optional integer return code "code" may be specified. |
30 | 34 | !
|
31 | 35 | ! Example
|
32 | 36 | ! -------
|
33 | 37 | !
|
34 | 38 | ! call error_stop("Invalid argument")
|
35 | 39 |
|
36 |
| -character(len=*) :: msg ! Message to print on stdout |
37 |
| -print *, msg |
38 |
| -stop 1 |
| 40 | +character(len=*) :: msg ! Message to print on stderr |
| 41 | +integer, intent(in), optional :: code |
| 42 | + |
| 43 | +integer :: returncode |
| 44 | + |
| 45 | +if(present(code)) then |
| 46 | + write(stderr,*) msg |
| 47 | + error stop code |
| 48 | +else |
| 49 | + error stop msg |
| 50 | +endif |
39 | 51 | end subroutine
|
40 | 52 |
|
41 | 53 | end module
|
0 commit comments