Skip to content

Commit d991ab0

Browse files
authored
Implementing examples for error & panic handling
1 parent 78aea30 commit d991ab0

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

errors/main.go

+39-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,43 @@
11
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+
*/
36
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+
}
435

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+
}
543
}

0 commit comments

Comments
 (0)