Home > front end >  What is the best way to handle indicating specific errors to the caller of this function in Python?
What is the best way to handle indicating specific errors to the caller of this function in Python?

Time:03-02

I have a function that has three possible points of failure that currently return False if the conditions are met:

 def validate(self, g):

        if self.turn_no > self.turn_limit:
            self.state = "loss"
            return False
        
        if self.state != "active":
            return False

        if self.__validate_guess(g) != True:
            return False

        self.turn_no = self.turn_no   1

        return guess

Based on how this function fails it will dictate how the caller of this function handles it.

For example if it is the first condition then I want to indicate that it failed because the turn count exceeded the turn limit, or for the third that the guess was invalid, etc.

How the function fails dictates how the caller responds to it.

I have considered returning a string or integer that corresponds to a certain meaning and adding this to the docs, but this seems.. wrong.

I have also considered raising exceptions, but how can I do this in such a way that indicates my application specific exceptions? Or are exceptions not the right answer either.

Thanks.

CodePudding user response:

Exceptions are exactly the tool designed for this situation. You can use already existing exceptions or implement new ones by inheriting from Exception class as can be seen in an example here. Then you simply raise whatever Exception is relevant to the cause for abnormal function exit.

CodePudding user response:

First you shoud create custom exceptions for example:

class MyFirstException(Exception):
    pass

class MySecondException(Exception):
    pass

class MyThirdException(Exception):
    pass

def validate(self, g):
    if self.turn_no > self.turn_limit:
        self.state = "loss"
        raise MyFirstException

    if self.state != "active":
        raise MySecondException

    if self.__validate_guess(g) != True:
        raise MyThirdException

    self.turn_no = self.turn_no   1

    return guess

If you would like to print additional message when exception is raised check this link

  • Related