try/catch
# Node.js
function foo(fail) {
if (fail) {
throw Error("my error");
}
}
function main() {
try {
foo(true);
} catch (err) {
console.log(`caught error: ${err.message}`);
}
}
main();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Output
caught error: my error
1
# Go
package main
import (
"errors"
"fmt"
)
func foo(fail bool) error {
if fail {
return errors.New("my error")
}
return nil
}
func main() {
err := foo(true)
if err != nil {
fmt.Printf("caught error: %s\n", err.Error())
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Output
caught error: my error
1
编辑 (opens new window)
上次更新: 2022/09/30, 11:34:22