Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python try except 0

Tags:

python

I am reading some python code written a while ago, and found this:

try:
    # do some stuff
except 0:
    # exception handling stuff

And I'm just not sure what except 0 means? I do have my guesses: Supposed to catch nothing i.e. let the exception propagate or it could be some sort of switch to turn debugging mode on and off by removing the 0 which will then catch everything.

Can anyone lend some insight? a google search yielded nothing...

Thanks!

Some sample code (by request):

            try:
                if logErrors:
                    dbStuffer.setStatusToError(prop_id, obj)
                    db.commit()
            except 0:
                traceback.print_exc()
like image 869
mlnyc Avatar asked Apr 05 '13 14:04

mlnyc


People also ask

How do you end an except in Python?

finally ..." in Python. In Python, try and except are used to handle exceptions (= errors detected during execution). With try and except , even if an exception occurs, the process continues without terminating. You can use else and finally to set the ending process.

How do I get around divide by zero error in Python?

The Python "ZeroDivisionError: float division by zero" occurs when we try to divide a floating-point number by 0 . To solve the error, use an if statement to check if the number you are dividing by is not zero, or handle the error in a try/except block.

What is try except finally in Python?

The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error. The finally block lets you execute code, regardless of the result of the try- and except blocks.

How do I raise ZeroDivisionError in Python?

A ZeroDivisionError is raised when you try to divide by 0. This is part of the ArithmeticError Exception class.


1 Answers

From what I understand, This is very useful for debugging purposes (Catching the type of exception)

In your example 0 acts as a placeholder to determine the type of exception.

>>> try:
...   x = 5/1 + 4*a/3
... except 0:
...   print 'error'
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: name 'a' is not defined
>>> try:
...   x = 5/0 + 4*a/3
... except 0:
...   print 'error'
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero

In the first case, the exception is NameError and ZeroDivisionError in the second. the 0 acts as a placeholder for any type of exception being caught.

>>> try:
...   print 'error'
... except:
... 
KeyboardInterrupt
>>> try:
...   x = 5/0 + 4*a/3
... except:
...   print 'error'
... 
error
like image 183
karthikr Avatar answered Oct 21 '22 19:10

karthikr