课程: Go Essentials: Concurrency, Connectivity, and High-Performance Apps

今天就学习课程吧!

今天就开通帐号,24,700 门业界名师课程任您挑!

Panic and recover

Panic and recover

- [Narrator] The usual method in Go for signaling errors is to return an error value. However, there are cases when there's an error you can't handle and you'd like to signal this. In Go there's a built-in panic function that will do just that. Let's have a look. So here I'm defining vals, which is a slice of three values. And now I'm going to access vals at location 10 and I'm going to add a Println just to make the compiler happy. Let's start with our debugging. And you see that I'm going to get a panic run time error index out of range. You can create panics by yourself by calling the panic function. But, this is not considered idiomatic Go and as we say in the Go proverbs, don't panic. Let me comment that out again. Let's say that I do want to guard against something that might panic. I can write a function, like safeValue. SafeValue gets files, a slice and an index and it's going to return an integer and a…

内容