LearnWave
Learn it. Master it.

Exception Handling in Python

Raising exceptions

Use raise and assert in a program.

When Python detects an error, it raises (or throws) an exception. A programmer can also raise one on purpose, when the program reaches a situation it should not continue in. There are two ways.

The raise statement: raise exception-name(optional message). For example, raise IndexError('No such element') stops the block and reports an IndexError with that message. Once an exception is raised, no further statements in that block are executed.

When an exception is raised, Python prints a stack traceback: the list of function calls that led to the error, from the first to the one where it happened. This shows exactly where things went wrong.

The assert statement: assert expression, message. Python checks the expression. If it is True, nothing happens and the program continues. If it is False, Python raises an AssertionError, with the message. For example, assert number >= 0, 'OOPS... Negative Number' stops the program with that message if number is -350.

assert is often used at the start of a function, to check that the input is valid before the function does any work.

In short: raise throws an exception directly; assert checks a condition and throws one only if the condition fails.

raise throws an exception; assert checks a condition first.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.