- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我是 Go 的新手,我正在尝试掌握 panic
函数。
到目前为止,我一直在使用这种类似的语法来处理程序中的错误:
func Find(i int) (item, error) {
// some code
if (not found) {
return nil, errors.New('Not Found')
}
// if found:
return myItem, nil
}
然后我偶然发现了 panic
函数。我很难理解它。是否有可能摆脱返回语句中的 error
并执行类似的操作?
func Find(i int) item {
// some code
if (not found) {
panic('Not found')
}
return myItem
}
如果是,调用函数时如何处理错误?
非常感谢
最佳答案
您想使用恢复
功能。
func Find(i int) item {
defer func() {
if e := recover(); e != nil {
// e is the interface{} typed-value we passed to panic()
fmt.Println("Whoops: ", e) // Prints "Whoops: Not Found"
}
}()
if (not found)
{ panic("Not Found")
}
return myItem
}
关于Golang错误处理: understanding panic,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28226395/
在Go(go1.2.1 linux/amd64)中运行http服务器时,我遇到了一个罕见的错误。 unexpected fault address 0xb84004 fatal error: faul
使用以下代码: var i interface{} = "hello" f, ok := i.(float64) fmt.Println(f, ok) f = i.(float64) // panic
考虑以下故意导致双重 panic 的代码: use scopeguard::defer; // 1.1.0 fn main() { defer!{ panic!() }; defer!
如果我传递给 std::panic::set_hook 的函数发生 panic 会怎样? 我可以想象对此做出多种 react :考虑这个 UB,中止程序 like C++ does ,为新的 pani
我有一个 string,当我想获取 i 索引处的值时它会崩溃,但是当我切出相同的 string 保持较低的索引值作为长度然后它不会 panic 。想知道 1 和 2 有何不同? func main()
看起来不可能从 panic 中的 panic 中恢复过来? func TestError(t *testing.T) { e := &myErr{p: false} fmt.Print
当我使用 cargo test 运行以下程序时: use std::panic; fn assert_panic_func(f: fn() -> (), msg: String) { let
在开发过程中,我遇到了崩溃,并显示了内核 panic 上传模式。 有没有办法以某种方式连接到设备并提取日志? 最佳答案 我希望这就是您正在寻找的...来源:StackOverflowAndroid 创
我需要制造内核 panic ,我尝试了以下操作 sysctl kernel.panic=0 && echo c > /proc/sysrq-trigger 当我运行上面的命令时。我看到系统总是重新启动
是否可以从 recover 中“重新抛出”错误并保留原始堆栈跟踪?我知道的最好的办法就是再次 panic ,但这确实会创建一个新的堆栈跟踪。 func do() { defer func()
我正在使用 panic::catch_unwind引起 panic : use std::panic; fn main() { let result = panic::catch_unwind
func sub(){ defer func (){ panic(2) }() panic(1) } func main(){ defer func()
考虑到我使用的是原始的“errors”go 包。 还有,panic(11) 和 panic("11") 之间的区别? 最佳答案 panic定义为 func panic(v interface{}),调
我是 golang 的新手。在定义位置后 try catch 主 block 中的错误后,我的程序出现 panic 。我在某处读过,添加 defer.close() 可能会有所帮助,但编译器再次说你的
有这种新的编程语言 V-lang由亚历克斯·梅德维尼科夫 (Alex Medvednikov) 创建。我目前使用的是 V-lang 0.1.11 版。我可以在 V-lang 中声明一个数组,如下所示:
在启动 linux 时,我在控制台上得到以下打印,并且系统挂起。 Waiting for root device /dev/mmcblk0p2... mmc_host mmc0: Bus speed
我已经实现了这个 answer 中提到的 goroutine 的生产者-消费者模式.但它有时会出现 panic ,并出现错误提示:“ panic :同步:负 WaitGroup 计数器”。我有如下示例
上下文: https://github.com/fusspawn/tserver/blob/master/app/controllers/gorp.go 作为尝试设置 gorm 的一部分,我尝试转换标
专注Golang,Python语言,云原生,人工智能领域得博主 过去经历的意义在于引导你,而非定义你, 只要我们足够努力,任何人都有无限潜力 panic 抛出异常函数 recove
这个问题在这里已经有了答案: How to return a value in a Go function that panics? (3 个回答) 2年前关闭。 package main impor
我是一名优秀的程序员,十分优秀!