Nearby lessons
78 of 159Python - Exception Handling
- Distinguish syntax errors from runtime errors (exceptions)
- Understand what happens when an exception is left unhandled
- Recognize that the goal of exception handling is graceful termination
- Learn the Python exception hierarchy - from BaseException down to specific errors
- Identify the direct child classes of BaseException
Introduction to Exception Handling
In any programming language, there are two types of errors possible.
- Syntax Errors
- Runtime Errors
1. Syntax Errors
The errors which occur because of invalid syntax are called Syntax Errors.
Here are two common examples:
Example 1
Example 2
Python 2 print syntax — shown for comparison, not runnable here.
print "Hello"Explanation
In the first example, the if statement is missing the colon (:).
In the second example, the print() function is called without parentheses, which is Python 2 syntax.
Because the syntax is incorrect, Python raises a SyntaxError before executing the program.
Important Note
The programmer is responsible for correcting syntax errors.
Only after all syntax errors are corrected will program execution start.
2. Runtime Errors (Exceptions)
Runtime Errors are also known as Exceptions.
While executing the program, if something goes wrong because of:
- End user input
- Programming logic
- Memory problems
- etc.
then we will get Runtime Errors.
Example 1
Example 2
Example 3
If the user enters ten instead of a number:
Explanation
Division by zero raises a ZeroDivisionError, dividing by an incompatible type raises a TypeError, and passing a non-numeric value to int() raises a ValueError.
Important Note
The Exception Handling concept is applicable only for Runtime Errors.
It is not applicable for Syntax Errors.
What is an Exception?
An unwanted and unexpected event that disturbs the normal flow of the program is called an Exception.
Examples of exceptions:
- ZeroDivisionError
- TypeError
- ValueError
- FileNotFoundError
- EOFError
Need for Exception Handling
It is highly recommended to handle exceptions.
The main objective of Exception Handling is Graceful Termination of the program.
Exception Handling does not mean repairing the exception. We have to define an alternative way to continue the remaining part of the program normally.
Conceptual Example
Suppose our programming requirement is to read data from a remote file located in London.
If, at runtime, the London file is not available, then the program should not terminate abnormally.
Instead, we should provide a local file and continue the remaining program normally.
Explanation
- The risky code is placed inside the
tryblock. - If the remote file is not available, a
FileNotFoundErroroccurs. - The
exceptblock provides an alternative solution by using the local file. - The remaining program continues normally instead of terminating abnormally.
Default Exception Handling in Python
Every exception in Python is an object, and for every exception type, the corresponding exception class is already available.
Whenever an exception occurs, the PVM (Python Virtual Machine) creates the corresponding exception object and checks whether exception handling code is available.
- If handling code is available, the exception is handled and the program continues normally.
- If handling code is not available, the Python Interpreter terminates the program abnormally, prints the exception information on the console, and the remaining statements are not executed.
Flow of Default Exception Handling
Program Starts
│
▼
Execute Statements
│
▼
Exception Occurs
│
▼
PVM Creates Exception Object
│
▼
Search for Handling Code
│
┌─────┴─────────┐
│ │
▼ ▼
Handling No Handling
Available Code
│ │
▼ ▼
Execute Abnormal
Handling Termination
Code │
│ ▼
▼ Print Exception
Continue Information
Program
Program
Program Explanation
print("Hello")executes successfully and printsHello.print(10/0)raises aZeroDivisionError. The PVM creates aZeroDivisionErrorobject and searches for handling code, but none is available.- The Python Interpreter terminates the program abnormally and prints the exception information.
print("Hi")is never executed.
Important Point - Every Exception is an Object
Whenever an exception occurs, the Python Virtual Machine creates the corresponding exception object:
10 / 0 ↓ ZeroDivisionError Object
Every Exception has a Class
For every exception type, Python already provides a corresponding exception class:
| Exception | Corresponding Class |
|---|---|
| ZeroDivisionError | ZeroDivisionError |
| TypeError | TypeError |
| ValueError | ValueError |
| FileNotFoundError | FileNotFoundError |
Python Exception Hierarchy
Every exception in Python is a class, and all exception classes are child classes of BaseException — either directly or indirectly.
Hence, BaseException acts as the root class of the Python Exception Hierarchy.
Exception Hierarchy Diagram
BaseException
│
├── Exception
│ │
│ ├── ArithmeticError
│ │ ├── ZeroDivisionError
│ │ ├── FloatingPointError
│ │ └── OverflowError
│ │
│ ├── AttributeError
│ │
│ ├── EOFError
│ │
│ ├── NameError
│ │
│ ├── LookupError
│ │ ├── IndexError
│ │ └── KeyError
│ │
│ ├── OSError
│ │ ├── FileNotFoundError
│ │ ├── InterruptedError
│ │ ├── PermissionError
│ │ └── TimeoutError
│ │
│ ├── TypeError
│ │
│ └── ValueError
│
├── SystemExit
├── GeneratorExit
└── KeyboardInterrupt
Explanation of the Hierarchy
Most of the time, as a programmer, we concentrate on the Exception class and its child classes:
- Exception is the parent class for most runtime exceptions.
- ArithmeticError covers arithmetic-related errors. Its child
ZeroDivisionErroris raised byprint(10/0). - LookupError covers lookup-related errors. Its children
IndexError(list index out of range) andKeyErrorare common. - OSError covers operating-system-related errors. Its child
FileNotFoundErroris raised when a file is missing.
Example - ArithmeticError
Example - LookupError
Example - OSError
Other Exception Classes
| Exception Class | When It Occurs |
|---|---|
| AttributeError | Accessing an attribute that does not exist. |
| EOFError | Input reaches End Of File unexpectedly. |
| NameError | Using an undefined variable. |
| TypeError | Operation performed on incompatible data types. |
| ValueError | Correct type but invalid value is supplied. |
Direct Child Classes of BaseException
Apart from the Exception class, BaseException also contains the following direct child classes:
- SystemExit
- GeneratorExit
- KeyboardInterrupt
These classes are not commonly used for normal application-level exception handling.
- Syntax errors are caught before execution; runtime errors occur during execution
- Exception handling means providing an alternative path, not repairing the exception
- When an exception occurs, the PVM creates an exception object and searches for handling code
- Without handling code, the interpreter terminates the program and prints the exception information
- BaseException is the root of the hierarchy; most runtime exceptions inherit from Exception