What is the difference between 2 code blocks

package main

import (
"fmt"
"github.com/sirupsen/logrus"
"runtime/debug"
"time"
)

func main() {

defer func() {
if err := recover(); err != nil {
logrus.Errorln("main", err)
debug.PrintStack()
}
}()
GoInside(nil)
time.Sleep(2 * time.Second)
fmt.Println("After panic")

}

type Test struct {
X int
}

func GoInside(v *Test) {
go NullPointer(v.X)
}
func NullPointer(X int) {
fmt.Println(X)

}


This above code can handle a panic error , but the code below can not handle a panic ==> why 

package main

import (
"fmt"
"github.com/sirupsen/logrus"
"runtime/debug"
"time"
)

func main() {

defer func() {
if err := recover(); err != nil {
logrus.Errorln("main", err)
debug.PrintStack()
}
}()
GoInside()
time.Sleep(2 * time.Second)
fmt.Println("After panic")

}

type Test struct {
X int
}

func GoInside() {
go NullPointer(nil)
}
func NullPointer(v *Test) {
fmt.Println(v.X)

}

 


Because  in the first code block, we calculated v.X before passing v.X to the go routine => panic happened before start calling to go routine => can handle this panic  

func GoInside(v *Test) {
go NullPointer(v.X)
}


But int the second code block, we start running go routine first, then inside go routine we calculated v.X => panic happened => main func can not handle this panic



Comments

Popular posts from this blog

Fixing the DeepSpeed Import Error While Fine-Tuning the Qwen Model

Amazon Linux 2023 - User data configuration for launch templates to connect to the EKS cluster

How to create ISM policy and rotate logs in opensearch