python calling custom exceptions from if-statement and try-except

29,567

Solution 1

In order not to raise the exception twice, you should wrap the try/except block around the if statemnt only, like so:

if something:
   try:
       #make an error
       ;fdsfas
    except Exception, e:
        raise CustomException(e.message, file='somefile.txt', var2='something')
else:
    raise CustomException('this is my custom message', file='somefile.txt', var2='something')

And in order to pass the custom exception some parameters you must provide that parameters to the constructor of the class just like you did in the if/else statement.

Solution 2

You could in the except block use:

if not isinstance(e, CustomException): raise CustomException(e)

Edit:

A sys.exc_info() before the raise inside the except will successfully remove the traceback to the source of the exception i.e. NameError.

Share:
29,567
sadmicrowave
Author by

sadmicrowave

Updated on July 09, 2022

Comments

  • sadmicrowave
    sadmicrowave almost 2 years

    So, I've created a custom exception that I want to call in 2 different ways (a if/else statement, and a try/except statement). Here is the custom exception:

    class CustomException(Exception):   
       def __init__(self, value=None, *args, **kwargs):
         self.parameter = value
         for key, value in kwargs.items():
             setattr(self, key, value)
    
         for key, value in self.__dict__.items():
             print "%s => %s" % ( key, value ) 
    
       def __str__(self):
         return repr(self.parameter)
    

    Here is how I am wanting to implement the custom exception:

    try:
       if something:
           #make an error
           ;lsdfj
       else:
           raise CustomException('this is my custom message', file='somefile.txt', var2='something')
    except Exception, e:
       raise CustomException(e)
    

    My issues, I believe, are two fold:

    1: When the standard NameError that is thrown in the try/except block (due to ;lsdfj), I want to pass CustomExceptions some extra parameters like 'file', just like the if/else implementation; how would I do that?

    2: When the custom exception is raised (from the if/else statement being false), the CustomExceptions class ends up being called twice, because I raise it in the if/else block then it gets raised again within the except: section. I don't know how to get around this.

    So, in the above case, I want to call CustomException when the if-statement is not true, and I want to call it when there is a standard exception thrown inside the code block... but currently, if something: evaluates to false then the CustomException will be raised twice...

    So I want the custom exception to be used unilaterally throughout my code for if/else conditions, and standard python exceptions...

    I know this explanation was convoluted but I'm not sure how else to explain what I'm after... Any help would be much appreciated! Thanks in advance!