Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raise an exception

Tags:

exception

go

I would want to raise an exception as it's made in Python or Java --to finish the program with an error message--.

An error message could be returned to a parent function:

func readFile(filename string) (content string, err os.Error) {
    content, err := ioutil.ReadFile(filename)
    if err != nil {
        return "", os.ErrorString("read " + filename + ": " + err)
    }
    return string(content), nil
}

but I want that it can be finished when the error is found. Would be correct the next one?

func readFile(filename string) (content string) {
    content, err := ioutil.ReadFile(filename)

    defer func() {
        if err != nil {
            panic(err)
        }
    }()

    return string(content)
}
like image 891
user316368 Avatar asked May 12 '10 12:05

user316368


Video Answer


1 Answers

By convention, Go doesn't do things like this. It has panic and recover, which are sort of exception-like, but they're only used in really exceptional circumstances. Not finding a file or similar is not an exceptional circumstance at all, but a very regular one. Exceptional circumstances are things like dereferencing a nil pointer or dividing by zero.

like image 196
Evan Shaw Avatar answered Sep 23 '22 06:09

Evan Shaw