Home > OS >  Raise a python exception without "raise" statement
Raise a python exception without "raise" statement

Time:08-19

Is it possible to raise an exception in Python without using raise statement?

For example, instead of raise ValueError use some method like ValueError.raise(). This question only relates to python built-in exceptions and not some custom exception classes that can be build from them.

CodePudding user response:

Define a helper function to raise the exception:

def raising(exc: BaseException):
    raise exc

This can then be used in any place an expression can be used, such as lambda or assignment expressions.

This approach can be used to make practically any statement usable as an expression. However, be mindful that statements are an important part of code readability - when in doubt, prefer to refractor the code so that the statement can be used in place.

CodePudding user response:

You can, just build a code that leads t generate an exception

  • ZeroDivisionError

    print("x")
    1 / 0
    
    Traceback (most recent call last):
    File "C:\Users\...\test_4.py", line 9, in <module>
    1 / 0
    ZeroDivisionError: division by zero
    
  • AssertionError

    print("x")
    assert 1 == 0, "custom message"
    
    Traceback (most recent call last):
    File "C:\Users\...\test_4.py", line 9, in <module>
    assert 1 == 0, "custom message"
    AssertionError: custom message
    
  • ...

  • Related