1
1
module stdlib_experimental_error
2
- use , intrinsic :: iso_fortran_env, only: stderr= >error_unit
2
+ use , intrinsic :: iso_fortran_env, only: stderr = > error_unit
3
+ use stdlib_experimental_optval, only: optval
3
4
implicit none
4
5
private
5
6
@@ -10,7 +11,7 @@ module subroutine error_stop(msg, code)
10
11
end subroutine error_stop
11
12
end interface
12
13
13
- public :: assert, error_stop
14
+ public :: assert, check, error_stop
14
15
15
16
contains
16
17
@@ -31,4 +32,49 @@ subroutine assert(condition, code)
31
32
if (.not. condition) call error_stop(" Assert failed." , code)
32
33
end subroutine
33
34
34
- end module
35
+ subroutine check (condition , msg , code , warn )
36
+
37
+ ! Checks the value of a logical condition. If condition == .false. and:
38
+ !
39
+ ! * No other arguments are provided, it stops the program with the default
40
+ ! message and exit code 1;
41
+ ! * msg is provided, it prints the value of msg;
42
+ ! * code is provided, it stops the program with the given exit code;
43
+ ! * warn is provided and .true., it doesn't stop the program and prints
44
+ ! * the message.
45
+ !
46
+ ! Arguments
47
+ ! ---------
48
+
49
+ logical , intent (in ) :: condition
50
+ character (* ), intent (in ), optional :: msg
51
+ integer , intent (in ), optional :: code
52
+ logical , intent (in ), optional :: warn
53
+ character (* ), parameter :: msg_default = ' Test failed.'
54
+
55
+ ! Examples
56
+ ! --------
57
+ !
58
+ ! ! Stops the program with exit code 1 and prints 'Test failed.'
59
+ ! call check(a == 5)
60
+ !
61
+ ! ! As above, but prints 'a == 5 failed.'
62
+ ! call check(a == 5, msg='a == 5 failed.')
63
+ !
64
+ ! ! As above, but doesn't stop the program.
65
+ ! call check(a == 5, msg='a == 5 failed.', warn=.true.)
66
+ !
67
+ ! ! As example #2, but stops the program with exit code 77
68
+ ! call check(a == 5, msg='a == 5 failed.', code=77)
69
+
70
+ if (.not. condition) then
71
+ if (optval(warn, .false. )) then
72
+ write (stderr,* ) optval(msg, msg_default)
73
+ else
74
+ call error_stop(optval(msg, msg_default), optval(code, 1 ))
75
+ end if
76
+ end if
77
+
78
+ end subroutine check
79
+
80
+ end module stdlib_experimental_error
0 commit comments