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:
| Exception | Raised when |
|---|---|
| SyntaxError | the code breaks Python's grammar |
| ValueError | a function gets an argument of the right type but an unsuitable value |
| IOError | a file cannot be opened |
| ImportError | a module cannot be found |
| EOFError | input() reaches the end of the file without reading any data |
| ZeroDivisionError | a number is divided by zero |
| IndexError | an index is outside the range of a list, tuple or string |
| NameError | a variable is used before it is defined |
| IndentationError | the indentation is wrong |
| TypeError | an operation is applied to a value of the wrong type |
| OverflowError | a calculation is too large to represent |
Programmers can also define their own exceptions, called user-defined exceptions, for errors specific to their program.
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.