Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Conditionally Catching Exceptions

Tags:

Is it possible to conditionally catch exceptions in python? I would like to be able to write a function so that the caller can decide who handles the exception.

Basically, I would like something like this:

def my_func(my_arg, handle_exceptions):     try:         do_something(my_arg)     except Exception as e if handle_exceptions:         print "my_func is handling the exception" 

I know I could write some kludgy code that does what I want, but I want a pythonic answer if there is one.
Thanks.

like image 881
speedplane Avatar asked Nov 16 '11 03:11

speedplane


People also ask

How do you catch exceptions in Python?

Catching Exceptions in Python In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.

How do you reraise the current exception?

Reraise the current exception If you pass zero to the second argument of the division() function, the ZeroDivisionError exception will occur. However, instead of handling the exception, you can log the exception and raise it again. Note that you don't need to specify the exception object in the raise statement.


1 Answers

You can re-raise the exception if you don't want to handle it:

def my_func(my_arg, handle_exceptions):     try:         do_something(my_arg)     except Exception, e:         if not handle_exceptions:             # preserve prior stack trace             raise              # Or, if you dont care about the stack prior to this point             #raise Exception(e)              # similarly, you can just re-raise e.  The stack trace will start here though.             #raise e         else:             print "my_func is handling the exception" 

Another option is to create your own exceptions that subclass Exception (or a specific exception like urllib2.HTTPError) and then only catch/throw (raise) your custom exception:

class MyException(Exception):     def __init__(self, message):         self.message = message  class MyExceptionTwo(Exception):     def __init__(self, message):         self.message = message     def __repr__(self):         return "Hi, I'm MyExceptionTwo.  My error message is: %s" % self.message  def something():     if not tuesday:         raise MyException("Error: it's not Tuesday.")     else:         raise MyExceptionTwo("Error: it's Tuesday.")  def my_func(my_arg):     try:         something()     except MyException, e:         print e.message     # Will pass MyExceptionTwo up the call chain  def my_other_func():     try:         my_func(your_arg)     except MyExceptionTwo, e:         print str(e)     # No need to catch MyException here since we know my_func() handles it     # but we can hadle MyExceptionTwo here 
like image 130
chown Avatar answered Sep 17 '22 15:09

chown