LearnWave
Learn it. Master it.

Exception Handling in Python

Errors and exceptions

Tell a syntax error from a run-time exception and name built-in exceptions.

Programs can go wrong in two different ways.

  • Syntax errors (also called parsing errors) break the grammar rules of Python: a missing colon, an unclosed bracket, a misspelt keyword. Python checks the whole program before running it, so a program with a syntax error does not run at all until the error is fixed.
  • Exceptions happen while the program is running, in code that is grammatically correct. Dividing by zero, opening a file that does not exist, or turning the word 'abc' into a number all cause exceptions.

In Python, an exception is an object that represents an error that happened during execution. (Strictly, SyntaxError is also an exception, but every other exception happens in code whose syntax is correct.)

For example, int('abc') has correct syntax, so the program starts. But int() cannot turn 'abc' into a number, so Python raises a ValueError: the argument is the right type (a string) but has the wrong value.

Python has many built-in exceptions. Some common ones:

ExceptionRaised when
SyntaxErrorthe code breaks Python's grammar
ValueErrora function gets an argument of the right type but an unsuitable value
IOErrora file cannot be opened
ImportErrora module cannot be found
EOFErrorinput() reaches the end of the file without reading any data
ZeroDivisionErrora number is divided by zero
IndexErroran index is outside the range of a list, tuple or string
NameErrora variable is used before it is defined
IndentationErrorthe indentation is wrong
TypeErroran operation is applied to a value of the wrong type
OverflowErrora calculation is too large to represent

Programmers can also define their own exceptions, called user-defined exceptions, for errors specific to their program.

Syntax errors stop a program starting; exceptions stop it running.

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.