Exception defined but shows undefined when raised in condition – Python

Question:

I have a custom exception defined but when I raise the error under a specific condition, I get to see "Exception not defined" error. Below is my code:

#difference between 2 arrays. If this variable is not null then my custom exception should fire up
tabs_diff = set(tabs_array) - set(tabs)

#custom exceptions 2
class FileComponentMismatch(Exception):
    """Throws when the sheet components does not match with the template
    Attributes:
        message -- explanation of the error
        diff -- component that is different
    """
    def __init__(self, message="The sheet does not have 26 components as in the template", diff=tabs_diff):
        self.message = message
        self.diff = diff
        super().__init__(self.message)
        super().__init__(self.diff)
    if tabs_diff is not None:
        raise FileComponentMismatch() #HERE IS WHERE THE ERROR THROWS

Any help on how this issue can be handled?

Asked By: Rick

||

Answers:

You shouldn’t use a class while defining it. That will work with java, but in python things get weird. usually you should define your exception, then change the code to use it somewhere else:

#difference between 2 arrays. If this variable is not null then my custom exception should fire up
tabs_diff = set(tabs_array) - set(tabs)

#custom exceptions 2
class FileComponentMismatch(Exception):
    """Throws when the sheet components does not match with the template
    Attributes:
        message -- explanation of the error
        diff -- component that is different
    """
    def __init__(self, message="The sheet does not have 26 components as in the template", diff=tabs_diff):
        self.message = message
        self.diff = diff
        super().__init__(self.message)
        super().__init__(self.diff)
        print("threw exception")
if tabs_diff is not None:
    raise FileComponentMismatch() #HERE IS WHERE THE ERROR THROWS

Answered By: KaliMachine
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.