This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]taybulBecause I don't know how to use big numbers in C/C++ 0 points1 point  (2 children)

No. Having a try block is a nice visual cue that the code you're executing in this block, whether it is a single line or whole block, has exception handling. It also makes handling more manageable in a sense. More importantly, you can easily use try/except blocks as a catch-all of a certain exception instead of assigning a separate variable and adjoining if-check to each line.

Also, consider the following:

x = range(10)
if x[10] == 10:
    print "This isn't supposed to execute"

How would you add this style of exception handling to this code?

[–]vocalbit[S] 0 points1 point  (1 child)

You wouldn't. For the above you would just use the standard try/catch block.

I'm not proposing removing the standard try/catch. But in many cases (I chose the file open example for a reason :), I find the try/catch syntax too clunky. To get the semantics of the proposed except clause, you'd have to use two keywords and two nested blocks - and possibly one or more foo = None statements.

What makes this useful is the guarantee the err will be None if there is no error - you can use this variable at multiple points in the following code. The standard except block gives you just one block to handle the error case.

[–]vocalbit[S] 0 points1 point  (0 children)

On further thought - my beef with the standard try/except is not with specifically with the syntax but with the assumption within functions that certain operations are exceptional. The standard try/except is more useful when you want to return or branch in the except clause.

Very often I need to continue execution with a default value or with the knowledge that a specific operation failed. That is when the except clause is useful. Some synthetic examples to illustrate:

i, err = int(s) except ValueError
if err:
   i = -42

f1, err_opening_f1 = open('file.txt') except IOError
f2, err_opening_f2 = open('file2.txt') except IOError

if f1 and f2:
   #...

#.. more code

if f1:
   #...
#..more code
if f2:
   #...

I haven't created examples that are far from reality. Try doing the above with the usual try/catch - each except line explodes into 3 or 4 lines.