Skip to content

Commit

Permalink
Don't Panic: Remove main panic
Browse files Browse the repository at this point in the history
In our example, we `panic` in `main` instead of the function `foo`. The
point that this was demonstrating was that the caller of the function
has the choice of panicking rather than `foo` itself.

Unfortunately, this causes confusion for readers modeling their `main()`
after this code, because the "good" example still panics.

This reduces confusion here by having `main` handle the `error` with an
`os.Exit`.

Note that this moves argument handling into `foo` because placing it in
`main` is not very testable.
  • Loading branch information
abhinav committed Sep 14, 2020
1 parent 209e1b8 commit d4b4568
Showing 1 changed file with 9 additions and 16 deletions.
25 changes: 9 additions & 16 deletions style.md
Original file line number Diff line number Diff line change
Expand Up @@ -1077,41 +1077,34 @@ allow the caller to decide how to handle it.
<tr><td>

```go
func foo(bar string) {
if len(bar) == 0 {
panic("bar must not be empty")
func run(args []string) {
if len(args) == 0 {
panic("an argument is required")
}
// ...
}

func main() {
if len(os.Args) != 2 {
fmt.Println("USAGE: foo <bar>")
os.Exit(1)
}
foo(os.Args[1])
run(os.Args[1:])
}
```

</td><td>

```go
func foo(bar string) error {
if len(bar) == 0 {
return errors.New("bar must not be empty")
func run(args []string) error {
if len(args) == 0 {
return errors.New("an argument is required")
}
// ...
return nil
}

func main() {
if len(os.Args) != 2 {
fmt.Println("USAGE: foo <bar>")
if err := run(os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if err := foo(os.Args[1]); err != nil {
panic(err)
}
}
```

Expand Down

0 comments on commit d4b4568

Please sign in to comment.