Raise a python exception without "raise" statement

Question:

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.

Asked By: Max Skoryk

||

Answers:

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
    
Answered By: azro

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.

Answered By: MisterMiyagi
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.