Search code examples
python-3.xexception

deliberately Raise and throw an exception in python


I have a use case where I need to raise an exception and again throw the exception. For this I'm using raise keyword in both try and catch. The code is as below

try:
    username = input ("username:")
    If Len(username) != 6:
        raise Exception
except Exception:
    raise Exception ("username is not valid")

Is this the right way to do like this? Is it compliant to coding standards to raise Exception in both try and except blocks?


Solution

  • I'm guessing this is a simplified version of your actual use case, in which case it is generally correct. A couple of notes:

    1. You can use raise without anything after it to re-raise the same error.
    try:
        raise ValueError('message')
    except ValueError:
        run_something()
        raise # will raise ValueError ('message')
    
    1. Don't raise a general Exception and don't catch them either, be specific, otherwise this code will obscure other errors and will be difficult to debug. If nothing else suits you, make an exception of your own:
    class MyException(Exception):
        pass
    

    Then you can use it:

    raise MyException('my message')
    

    In your use case, if I understood it correctly, all of this together would be:

    class InvalidUsername(Exception):
        pass
    
    try:
        username = input('username: ')
        if len(username) > 6:
            raise InvalidUsername('Username is too long')
        if '!' in username:
            raise InvalidUsername('Invalid character in username')
    except InvalidUsername:
        handle_invalid_user()
        raise
    

    Example in the console:

    >>> try:
    ...     username = input('username: ')
    ...     if len(username) > 6:
    ...         raise InvalidUsername('Username is too long')
    ...     if '!' in username:
    ...         raise InvalidUsername('Invalid character in username')
    ... except InvalidUsername:
    ...     handle_invalid_user()
    ...     raise
    ...
    username: test1234
    Traceback (most recent call last):
      File "<stdin>", line 4, in <module>
    __main__.InvalidUsername: Username is too long
    

    Or with an invalid character:

    username: ofer!
    Traceback (most recent call last):
      File "<stdin>", line 6, in <module>
    __main__.InvalidUsername: Invalid character in username