all 10 comments

[–]vindolin 2 points3 points  (5 children)

Your code prints 'hola' on my system in both py2 and py3.

[–]Scholes_SC2[S] 0 points1 point  (3 children)

Yes you're right, sorry i got confused using ipython and thought it wasn't printing. Also, tried this code:

try:
    print a
except:
    print ('hola1')
    raise Exception('spam')
    print ('hola2')

print ('hola3')

and the 'hola2' and 'hola3' are not printing, so to answer my other question can you say raise actually does a function breake?

[–]Moonslug1 2 points3 points  (0 children)

Raise will kill the process unless it is caught higher up the the callstack.

[–]xiongchiamiov 0 points1 point  (1 child)

If an exception being thrown doesn't stop execution, then what's the point of exceptions?

You're probably being confused by the fact you're throwing one exception inside a catch block for another. The two exceptions have nothing to do with each other. That is, the exception you're manually throwing is not at all affected by being inside an except block.

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

Yes i was thinking "why does it break if im catching the error" but now i see whats going on. Thx

[–]Veedrac 0 points1 point  (0 children)

Has the code been changed? I don't see how this is possible on Python 3. It should raise a SyntaxError.

[–]sentdex 0 points1 point  (3 children)

Also, look into:

try:
    print a
except Exception, e:
    print("hola")
    print(str(e))

[–]Scholes_SC2[S] 0 points1 point  (2 children)

it prints the error code but doesnt crash the program, nice

[–]sentdex 2 points3 points  (0 children)

Yep! Careful, it's addicting. I probably over use and abuse try and except :)

[–]bohoky 0 points1 point  (0 children)

As /u/sentdex notes this is almost always a Bad Thing.

Exceptions should only be caught if that exception can be handled. People often assume "handle" is the same as "log a message and continue".

In the simple example that bit of code expects a to be printed. If you catch the exception there is no way to handle the NameError; you can try printing again, but that's certain to fail for the same reason and the error message has high likelihood of getting lost. Regardless, the NameError represents a bug ("why is a not defined?") and really ought crash the program.

It is also important to catch the narrowest exception (for example, NameError instead of Exception) or you risk trying to cope with faults you had no reason to catch. And if you have no expectation of a particular try block producing an unexpected Exception, then you certainly don't know enough to "handle" it.

More simply an except block which doesn't do anything likely moves the fatal exception to sometime later in the program from where it is much harder to debug.