Handling panic in C code in GoLang

package main

/*
int mydiv(int a, int b){
return a/b;
}
*/
import "C"
import (
“fmt”
“runtime”
“sync”
)

func main() {

defer func() {
    if r := recover(); r != nil {
        fmt.Println("Recovered call to div", r)
    }
}()


div()

}

func div() {
var wg sync.WaitGroup
defer func() {
if r := recover(); r != nil {
fmt.Println(“Recovered div panic”, r)
}
}()

wg.Add(1)
runtime.LockOSThread()


go cgoPanic(&wg)
wg.Wait()

}

func cgoPanic(wg *sync.WaitGroup) {

fmt.Println(C.mydiv(10, 0))
//panic("Panicking in Go...")

}

I’m trying to handle C panics in GoLang, The sample code is as shown above. I tried using recover in the previous goroutine,but doesnt seem to work. Is there any way other than recover to handle C panics in GoLang code.The panic is as shown below

fatal error: unexpected signal during runtime execution[signal 0xc0000094 code=0x0 addr=0x0 pc=0x4a4c65]
runtime stack:invalid spdelta 0x4a4c50 0x4a4c65 0x456b7 -1runtime.gothrow(0x510570, 0x2a) c:/go/src/runtime/panic.go:503 +0x8eruntime.sigpanic() c:/go/src/runtime/os_windows.go:36 +0x65invalid spdelta 0x4a4c50 0x4a4c65 0x456b7 -1_cgo_23d1ba16528e_Cfunc_mydiv() ?:0 +0x15
goroutine 5 [syscall, locked to thread]:runtime.cgocall_errno(0x4a4c50, 0xc08201bf50, 0x0) c:/go/src/runtime/cgocall.go:130 +0xdb fp=0xc08201bf30 sp=0xc08201bf08main._Cfunc_mydiv(0xa, 0x0) /C/TESTGO/src/main/_obj/_cgo_gotypes.go:24 +0x4a fp=0xc08201bf50 sp=0xc08201bf30main.cgoPanic(0xc082004620) C:/TESTGO/src/main/Testmain.go:48 +0x78 fp=0xc08201bfd8 sp=0xc08201bf50runtime.goexit() c:/go/src/runtime/asm_amd64.s:2232 +0x1 fp=0xc08201bfe0 sp=0xc08201bfd8created by main.div C:/TESTGO/src/main/Testmain.go:37 +0x85
goroutine 1 [semacquire, locked to thread]:sync.(*WaitGroup).Wait(0xc082004620) c:/go/src/sync/waitgroup.go:132 +0x170main.div() C:/TESTGO/src/main/Testmain.go:38 +0x95main.main() C:/TESTGO/src/main/Testmain.go:23 +0x3c
goroutine 17 [syscall, locked to thread]:runtime.goexit() c:/go/src/runtime/asm_amd64.s:2232 +0x1

It fails as “unexpected signal during cgo execution”

You always need to be in the same goroutine to recover a panic, regardless of where it originates.

I strongly recommend not attempting to recover this panic, though. A problem in C land would have crashed a C program and should probably do so in your case as well. Recovering “unknown” panics in Go is bad practice as you’re unsure of what state the program might be in, and this is doubly true when C code is involved. Don’t do it. :wink:


You can add triple backticks before and after your code to display it properly. I’d help out but I don’t have edit rights. I.e.,

```
code goes here
```

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.