File tree 1 file changed +39
-1
lines changed
1 file changed +39
-1
lines changed Original file line number Diff line number Diff line change 1
1
package errors
2
-
2
+ /*
3
+ In golang it is perfectly normal for functions & methods to return an error to indicate an exception
4
+ which differs greatly from most languages. By convention the error should be the last item returned.
5
+ */
3
6
func Run () {
7
+ returningAnError (15 )
8
+ handlingAnError ()
9
+ recoveringIfPanics ()
10
+ }
11
+
12
+ type MyNewError struct {
13
+ number int
14
+ }
15
+
16
+ func (m * MyNewError ) Error () string {
17
+ return fmt .Sprintf ("%d was less than 10!" , m .number )
18
+ }
19
+
20
+ // An example of conditionally returning an error under some circumstance.
21
+ func returningAnError (argument int ) (int , error ) {
22
+ if argument < 10 {
23
+ return argument , & MyNewError (number : argument )
24
+ }
25
+ return argument , nil
26
+ }
27
+
28
+ // How to handle an error, 'raising' if something bad happens
29
+ func handlingAnError () {
30
+ value , err := returnAnError (100 )
31
+ if err != nil {
32
+ panic (err )
33
+ }
34
+ }
4
35
36
+ // Panics can be 'caught' and handled using the `recover` builtin idiom
37
+ func recoveringIfPanics () {
38
+ defer func () {
39
+ if r := recover (); r != nil {
40
+ fmt .Println ("Recovered from error:\n " , r )
41
+ }()
42
+ }
5
43
}
You can’t perform that action at this time.
0 commit comments