Search code examples
pythonexceptionif-statementerror-handlingcustom-exceptions

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


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!


Solution

  • 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.