About catching ANY exception

Posted on

Solving problem is about exposing yourself to as many situations as possible like About catching ANY exception and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about About catching ANY exception, which can be followed any time. Take easy to follow this discuss.

About catching ANY exception

How can I write a try/except block that catches all exceptions?

Answer #1:

You can but you probably shouldn’t:

    print "Caught it!"

However, this will also catch exceptions like KeyboardInterrupt and you usually don’t want that, do you? Unless you re-raise the exception right away – see the following example from the docs:

    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
    print "Unexpected error:", sys.exc_info()[0]
Answered By: Tim Pietzcker

Answer #2:

Apart from a bare except: clause (which as others have said you shouldn’t use), you can simply catch Exception:

import traceback
import logging
except Exception as e:
    # Logs the error appropriately. 

You would normally only ever consider doing this at the outermost level of your code if for example you wanted to handle any otherwise uncaught exceptions before terminating.

The advantage of except Exception over the bare except is that there are a few exceptions that it wont catch, most obviously KeyboardInterrupt and SystemExit: if you caught and swallowed those then you could make it hard for anyone to exit your script.

Answered By: Duncan

Answer #3:

You can do this to handle general exceptions

    a = 2/0
except Exception as e:
    print e.__doc__
    print e.message
Answered By: vwvolodya

Answer #4:

To catch all possible exceptions, catch BaseException. It’s on top of the Exception hierarchy:

Python 3:

Python 2.7:

except BaseException as error:
    print('An exception occurred: {}'.format(error))

But as other people mentioned, you would usually not need this, only for specific cases.

Answered By: gitaarik

Answer #5:

Very simple example, similar to the one found here:


If you’re attempting to catch ALL exceptions, then put all your code within the “try:” statement, in place of ‘print “Performing an action which may throw an exception.”‘.

    print "Performing an action which may throw an exception."
except Exception, error:
    print "An exception was thrown!"
    print str(error)
    print "Everything looks great!"
    print "Finally is called directly after executing the try statement whether an exception is thrown or not."

In the above example, you’d see output in this order:

1) Performing an action which may throw an exception.

2) Finally is called directly after executing the try statement whether an exception is thrown or not.

3) “An exception was thrown!” or “Everything looks great!” depending on whether an exception was thrown.

Hope this helps!

Answered By: Joshua Burns

Answer #6:

There are multiple ways to do this in particular with Python 3.0 and above

Approach 1

This is simple approach but not recommended because you would not know exactly which line of code is actually throwing the exception:

def bad_method():
        sqrt = 0**-1
    except Exception as e:

Approach 2

This approach is recommended because it provides more detail about each exception. It includes:

  • Line number for your code
  • File name
  • The actual error in more verbose way

The only drawback is tracback needs to be imported.

import traceback
def bad_method():
        sqrt = 0**-1
    except Exception:
Answered By: grepit

Answer #7:

I’ve just found out this little trick for testing if exception names in Python 2.7 . Sometimes i have handled specific exceptions in the code, so i needed a test to see if that name is within a list of handled exceptions.

    raise IndexError #as test error
except Exception as e:
    excepName = type(e).__name__ # returns the name of the exception
Answered By: Danilo

Answer #8:

    # this will catch any exception or error

It is worth mentioning this is not proper Python coding. This will catch also many errors you might not want to catch.

Answered By: Yuval Adam

Leave a Reply

Your email address will not be published. Required fields are marked *