by cletus · 14y ago · 0 comments
There are two general use cases for exceptions:
1. Unexpected (typically fatal) problems;
2. As an alternative to multiple return values.
(1) is things like out of memory errors. (2) is things like you're trying to parse a user input into a number and it fails. I despise (2) for exceptions. It means writing code like:
try:
f = float(someText)
catch ValueError:
# I just parsed you, this is crazy,
# here's an exception, throw it maybe?
where this gets particularly irritating is when you start writing code like this: try:
doSomething()
catch ValueError:
pass
I nearly always end up writing wrapper functions around that crap.Java is worse for this because some libraries (including standard ones) abuse checked exceptions for this. I actually prefer:
if f, err := strconv.ParseFloat(text); err != nil {
// do something
}
or even: f, _ := strconv.ParseFloat(text);
for this kind of scenario.For the truly bad--typically fatal--error conditions and cleanup, IMHO defer/panic actually works quite well. I certainly prefer this:
f := File.Open('foo')
defer f.Close()
// do stuff
to: try:
f = open('foo')
# do stuff
finally:
if f:
f.close()
as Go puts the two relevant things together.Don't get me wrong: I like Python too but I do think Go has a lot going for it and has a bright future.
If you're going to use return values to indicate errors (and certainly I feel that there are reasons to use them, exceptions vs error codes is not an either/or proposition IMO), you should use sum types and return either an error or the correct value and have a mechanism to make sure you handle both cases.
ML and Haskell get this right, it's a shame Go overlooked them in this regard.
Why would you even be interested in the float when there's an error?
But in order to live in peace you have to either:
* Force every programmer to always check all the error values.
or
* Allow errors to pass silently.
So either you accept Go as a heavy-duty, heavy boilerplate error handling laden language. Or you accept it as a flaky, risky language.
Exceptions are the better compromise in my opinion. You get much cleaner code.
If this is the more common pattern for your programming life:
try:
f = float(someText)
use_it_here(f)
use_it_there(f)
catch Exception:
# I wanted to do things, but something went wrong.
# Here's what to do now, this is easy
Then you're better off using exceptions. If you need to check every single call (e.g. NASA or Kernel programming) then you might prefer this: if f, err := strconv.ParseFloat(text); err != nil {
// do something
}
if f, err := use_it_here(text); err != nil {
// do something
}
if f, err := use_it_there(text); err != nil {
// do something
}Given this, I don't see how Go is any worse with respect to sloppy programmers. They'll Always Find A Way.
Also, why couldn't your second example be nested? It seems like either of those two examples could be structured identically to the other.
Errors should never pass silently
Unless explicitly silenced
The problem with go is that you have 3 error modes:1. Explicitly handle everything
2. Implicitly silence sometimes
3. Panic/recover explodes sometimes (who knows where/when?)
Mode #2 is dangerous.
Java/Python give you 2 only modes:
1. Implicitly explode on error.
2. Explicitly silence sometimes.
Where both modes aren't inherently dangerous, i.e. they won't directly cause undefined states to execute.
--------------------
Concerning the nesting in my examples - I'm used to the style of C programming where failing is mostly handled by a return as to keep the program as readable (and thus flat) as possible. So pardon my french but I assumed "// do something" would somehow prevent further usage of 'f'.
Note that the Go example, although tedious, isn't bad in cases where you really do need to check every single possible error.
You could certainly argue for handling each message in a separate process a la erlang, but this approach worked well for us.
I think checked exceptions were a mistake (IIRC Gosling agrees), and Java could do with better support for multiple return values (which exceptions get abused for), but I like Java-style runtime exceptions.
I'm pretty sure you wouldn't do that. You'd have a shallow tree of processes, each leaf process would be tasked with doing message processing e.g. provided by its supervisor. The supervisor would "manage the queue" so to speak, and depending on the semantics of the queue it would have 1 to n children; and it would be tasked with marking failed messages when a child process would blow up (and restarting a new child).
Modelling messages as processes would likely be impractical.
with open("x.txt") as f:
#do stuff with f
That's it. Obviously, compared to 'defer', it hides stuff - the actual magic happens in special methods __enter__ and __exit__ of the object passed to 'with'. def withSomeResource
handle = acquireSomeResource
yield handle
ensure
freeSomeResource(handle) if handle
end
withSomeResource do |h|
h.whatever
end
File.open and other parts of the standard library does that by default. I imagine the Python implementation of "with" is pretty similar, given that it can be implemented pretty much like this in Ruby, and "(begin) .. ensure .." is pretty much equivalent to "try ... finally ..": def with r
r.__enter__
yield(r)
ensure
r.__exit__
endPython's 'with' inverts the control - the control is with the language runtime and the resource is passive here. In fact 'with' is a special syntax extension, with calls to hard coded method names (__enter__ and __exit__) done by the Python runtime. The resource itself (or the contextmanager representing it) only implements __enter__ and __exit__ and is passive with regards to this mechanism.
Where the method is doesn't matter, e.g. the (incomplete) example I gave of implementing "with" in Ruby that shows a method that can be defined in the global "main" scope or wherever you want.
Some classes implement class-methods to instantiate an object and pass it to a black and free the resource as a convenience, such as File.open, but it could go wherever else.
The resource itself most certainly does not need to know a thing about it as long as its API lets you do the cleanup you want/need.
> The control is with the resource.
The control is with whatever calls yield. Whether that be a method on the global "main" object (closest thing Ruby has to a global, freestanding function) or on the class of the resource itself, or an explicit "begin ... ensure ... end" block if you only need it once.
> In fact 'with' is a special syntax extension, with calls to hard coded method names (__enter__ and __exit__) done by the Python runtime.
Which is why I gave my example of how I thought "with" would look like in Ruby (as it turns out I missed some exception handling in order for it to be equivalent to the Python version in functionality).
Note that there's a difference in the handling of exceptions: if an exception is triggered from the `with` block, it is intercepted, provided to __exit__ and can be silenced if needed or desired (by returning a truthy value). So a closer approximation would be:
def with r
r.__enter__
begin
yield(r)
rescue Exception => e
raise unless r.__exit__(e)
else
r.__exit__(nil)
end
endThen again, `f.Close()` could hide any "magic" you want as well.
try (FileInputStream f = new FileInputStream(path)) {
// do stuff
}No, you have it exactly backwards. It's with return values that you have to check after every call to be safe. With exceptions you can truly say: if I don't know what to do if this fails then I don't do anything. You can let the exception bubble up higher, all the way up to crashing the program if you like (which gives a nice stack trace that can then be debugged).
With return values, if you don't check then you could be building up more and more trash and you won't even know it until you either hit a point of code that finally does look at what's returned, or if an exception occurs (e.g. segfault).
try:
f = float(someText)
catch ValueError:
# I just parsed you, this is crazy,
# here's an exception, throw it maybe?
Formatted That For You with open('foo') as f:
# do stuff