views:

124

answers:

2

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)
}
A: 

In java, in your application main function:

public class App 
    public static void main(String[] args) { 
        try { 
           // logic
        } catch ( ExitProgramException ex) { 
           // exit program
        } 
    }
}

Then throw ExitProgramException whenever you want to forcibly exit the program.

You could event craft an exception that overrides ExitProgramException.toString() -> it prints itself to the console and then forcibly exits with System.exit();

I wouldn't advise it, but it's possible.

Chris Kaminski
This is a question about Go, not Java.
Quartz
+3  A: 

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.

Evan Shaw
That depends on the level of the application. For quick and dirty scripts, prototypes, etc., it may very well be an unrecoverable error; not because it can't be done, but because it's not worth the effort to write those three lines.
Jurily
Fair enough. Just don't do this kind of thing in a released package or application and expect me to use it. :)
Evan Shaw