4 ms·
So you call say 3 methods, and at the end you have a "file not found" error... which call resulted in that failure? I don't know Scala specifically, but from w
by NateDad 12y ago
So you call say 3 methods, and at the end you have a "file not found" error... which call resulted in that failure? I don't know Scala specifically, but from what I know of most languages that support this kind of chaining, you can't tell. And that's the problem. Did your initialization fail to find it's config file in step 1? Did you fail to find the target file you were going to transform in step 2? Was there some other failure in step 3? You can't tell, so you can't actually handle the error.
This is effectively like doing this in Java:
try {
DoX()
DoY()
DoZ()
} catch( Exception ) {
// The code has no idea what failed here.
}
Whereas, the go code looks like this:
if err := DoX(); err != nil {
// handle error from DoX
}
if err := DoY(); err != nil {
// handle error from Doy
}
if err := DoZ(); err != nil {
// handle error from DoZ
}
This is what Go programmers means when they say "actually handle the errors". At each step you handle the specific failure from the specific call. It's somewhat more verbose, but it's a LOT more robust against real life failures.
- pcwalton 12y agoYou'd have the same effect (you don't know what specific call failed) if all of the comment lines said "return err", which is a common pattern in Go. The Scala approach mentioned is just sugar for that. You can of course handle each case separately if you want in Scala, just as you can in Go, but the common pattern has sugar.
- frowaway001 12y agoWhat? Actually, absolutely not. If you only care about whether something succeeded use Option, if you care about the error use Either, Validation, etc. Just pick the right Monad.
- pcwalton 12y agoYes, I agree, but I don't see how that's related to what I said.
- frowaway001 12y agoThen maybe don't comment?
- eropple 12y ago> So you call say 3 methods, and at the end you have a "file not found" error... which call resulted in that failure? The first exception hit pops out the other side and you pattern-match against it. So, the one that did file access and returned a FileNotFoundException. If you have multiple pieces of code that can return FileNotFoundExceptions, you can pass a message in the exception, just like any other Java exception. You can often be more type-specific, too. Bear in mind that defining a new exception in Scala is a one-liner, and you can encapsulate your FileNotFoundException in a RetrievalFailedException very easily and cleanly. Your method is not more robust, I assure you--it's just verbose and both typo- and thinko-prone.