4 ms·
Well, let's assume Go did commonly make use of exception handlers for error cases: defer func() { if r := recover(); r != nil { fmt.P
by randomdata 2y ago
Well, let's assume Go did commonly make use of exception handlers for error cases:
defer func() {
if r := recover(); r != nil {
fmt.Println("Failed to write file", r)
}
}()
f := os.Create("file")
defer f.Close()
io.WriteString(f, "Hello, World!")
Cool. You've solved one problem layer, perhaps. But if you look closely you'll notice that code still has a bug!
So clearly exception handlers aren't enough. There might be some good ideas in using exception handling, but if you strictly limit its use to errors you end up half-assing it. Why not go all the way and find a solution that works in all cases?
- matt_craig 2y agoIs it that the defer() that recovers is called before the defer() that closes (and potentially fails)?
- randomdata 2y agoNo. No rearranging of the code would fix the problem.
- matt_craig 2y agoHmm. Checked the docs, looks like os.Create returns *File and err, but the sample doesn’t check that error.
- randomdata 2y agoos.Create, per the topic of discussion, is said to throw an error using the exception handling mechanism rather than return error. The exception handler checks the error. If you focus on errors, you’re going to never get it. The whole idea here is that the problem is bigger than errors.
- xg15 2y agoMaybe I'm too dumb too see the bug here. Do you mean the issue that if both WriteString() and Close() throw an exception, the one from WriteString() will be swallowed? That used to be a problem, but has been solved in more modern implementations using suppressed exception tracking.
- randomdata 2y agoHa. I suppose you could argue that is also a bug, but not the one I was thinking of. Let's say this hypothetical Go where error over exception handling is the norm has no such issue. Think more carefully about what we're actually trying to solve. It is not just about errors.