Skip to content

Commit

Permalink
Recover - a poor man's catch ;)
Browse files Browse the repository at this point in the history
  • Loading branch information
CodingCrisis committed Feb 4, 2023
1 parent 982cb9c commit 7deceaf
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
21 changes: 20 additions & 1 deletion 16_panic.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"fmt"
"net/http"
"log"
)

func pan1(){
Expand All @@ -15,14 +16,31 @@ func pan1(){
func pan2(){
// Custom panic
fmt.Println("start")
// panic happens after defered statements
defer fmt.Println("this was deferred")
panic("something bad happened")
fmt.Println("end")
}

func pan3(){
// Custom panic
fmt.Println("start")
// Defering an anonymous function call - a call, so there are parentheses at the end
defer func(){
// recover returns nil if everything is ok (app is not panicing)
// else it's returning the actual error
if err := recover(); err != nil {
log.Println("Error:", err)
}
}()
panic("something bad happened")
fmt.Println("end")
}

// Custom web app
// returns Hello Go, on https://localhost:8080/
// panics when port is blocked, so trying to run a second copy of the app will panic
func pan3(){
func pan4(){
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){
w.Write([]byte("Hello Go!"))
})
Expand All @@ -36,4 +54,5 @@ func main(){
//pan1()
//pan2()
pan3()
//pan4()
}
28 changes: 28 additions & 0 deletions 17_recover.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package main

import(
"fmt"
"log"
)

func main(){
fmt.Println("start")
panicker()
fmt.Println("end")
}

func panicker(){
fmt.Println("about to panic")
defer func(){
if err := recover(); err != nil {
log.Println("Error:", err)
// if the error is serious we can re-panic
// in that case the main function will panic as well
// without the panic, only this internal function will stop executing
// main will live on and print the "end" text
//panic(err)
}
}()
panic("something bad happened")
fmt.Println("done panicking")
}

0 comments on commit 7deceaf

Please sign in to comment.