Python what is raise and assert statement

Manoj Jadhav
2 min readDec 8, 2017

--

When we writing code we generally add try/except block or assert statements. Sometimes we didn’t understand what actually difference between raise or assert statement.

Here I will tell you about my realisation about try/except, raise and assert statements.

try/except blocks let you catch and we can manage exception or add custom exceptions. Exceptions can be triggered by raise, assert, and a large number of errors such as trying to index an empty list or Integrity errors.

raise is typically used when you have detected an error condition or some condition does not satisfy. assert is similar but the exception is only raised if a condition is met.

raise and assert have a different philosophy.

There are many "normal" errors in code that you detect and raise errors. like HTTP error code (2xx, 4xx).

Assertions are generally reserved for “I swear this cannot happen” issues that seem to happen anyway. Its more like runtime debugging than normal runtime error detection. Assertions can be disabled if you use the -O flag or run from .pyo files instead of .pyc files, so they should not be part of regular error detection.

If production quality code raises an exception, then figure out what you did wrong. If it raises an AssertionError, you've got a bigger problem.

In short:

raise - raise an exception.

assert - raise an exception if a given condition is meet.

try - execute some code that might raise an exception, and if so, catch it.

Python’s assert statement is a debugging aid, not a mechanism for handling run-time errors. The goal of using assertions is to let developers find the likely root cause of a bug more quickly. An assertion error should never be raised unless there’s a bug in your program.

--

--