DEV Community

loading...

Discussion on: Golang through the eyes of a Java developer - pros and cons

robindiddams profile image
Robin Diddams

wait so you call functions that could throw exceptions but dont handle them until you find that they do throw? I was under the assumption you would still always check but would just prefer to do that check at a higher level (ie. wrap doJob in some error handling), but if you want to ignore errors just don't check them:

// assuming doNTask returns a string and an error
func doJob() []string {
    result1, _ := doFirstTask()
    result2, _ := doSecondTask()
    result3, _ := doThirdTask()

    return []string {
        result1,
        result2,
        result3,
    }
}
Enter fullscreen mode Exit fullscreen mode

lmk if im not understanding you correctly

Thread Thread
mraszplewicz profile image
Maciej Raszplewicz Author

Of course, it is not that I totally ignore all errors/exceptions, I want to handle them (as you have written) "at a higher level". Probably also I don't always know all the exceptions that can be thrown.

And if I ignore an error like in your example, my program will continue to work i.e. all functions doFirstTask, doSecondTask and doThirdTask will be executed. I want my doJob function to fail after the first error. I can achieve that with panic but it is not a good solution too and not idiomatic.

Thread Thread
alainvanhout profile image
Alain Van Hout • Edited

Think of it like this: your code is made up of lots of functions calling lots of other functions that are calling lots of other functions. If something goes wrong somewhere, then it's not necessarily the function right above that one that's best placed to handle the error. A thrown exception allows the error to bubble up automatically until the level on which it makes sense to handle the error.

For example, if I have a complex algorithm that at some point does a division by zero, then the code calling the complex algorithm will need to e.g. use a fallback or notify the user of the error. In either case, it's not the algorithm function right above the error that is able to do anything useful with the division by zero error.