Search code examples
pythonerror-handlingcoding-style

Is there a more elegant way of raising error in Python?[specific case]


I'm totally new to Python and programming in general, so I'm not too familiar with good practices or writing my code in a most sufficient / clear way. I've written this function for some math operations and I want Python to handle some exceptions.

def sqrt_of_sum_by_product(numbers: tuple) -> float:
        if prod(numbers) <= 0:  # checking if the result is a positive num to prevent further operations
            raise ValueError('cannot find sqrt of a negative number or divide by 0')
        return float("{:.3f}".format(math.sqrt(sum(numbers) / prod(numbers))))

This code works and I think it's clear enough, but I'm not sure if raising exception like I did is a good practise, and I couldn't find an answer.


Solution

  • Yes it's a good practice, but sometimes you may want to create your own errors. For example :

    class MyExeption(Exception):
        _code = None
        _message = None
        def __init__(self, message=None, code=None):
            self._code = message
            self._message = code
    

    And now you can do :

    def sqrt_of_sum_by_product(numbers: tuple) -> float:
            if prod(numbers) <= 0:  # checking if the result is a positive num to prevent further operations
                raise MyExeption('cannot find sqrt of a negative number or divide by 0', 'XXX')
            return float("{:.3f}".format(math.sqrt(sum(numbers) / prod(numbers))))