Nearby lessons

78 of 159

Python - Exception Handling

📌 What You Will Learn
  • 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.

  1. Syntax Errors
  2. Runtime Errors

1. Syntax Errors

The errors which occur because of invalid syntax are called Syntax Errors.

Here are two common examples:

Example 1

🐍Code Cell
1x = 10
2 
3if x == 10
4 print("Hello")
Output
SyntaxError: expected ':'

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

🐍Code Cell
1print(10 / 0)
Output
ZeroDivisionError: division by zero

Example 2

🐍Code Cell
1print(10 / "ten")
Output
TypeError: unsupported operand type(s) for /: 'int' and 'str'

Example 3

If the user enters ten instead of a number:

🐍Code Cell
1x = int(input("Enter Number:"))
2print(x)
Output
Enter Number: ten
ValueError: invalid literal for int() with base 10: 'ten'

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.

🐍Code Cell
1try:
2 read data from remote file located in london
3 
4except FileNotFoundError:
5 use local file and continue rest of the program normally
Output
No output captured.

Explanation

  • The risky code is placed inside the try block.
  • If the remote file is not available, a FileNotFoundError occurs.
  • The except block 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

🐍Code Cell
1print("Hello")
2 
3print(10/0)
4 
5print("Hi")
Output
Hello

Traceback (most recent call last):
  File "test.py", line 2, in 
    print(10/0)

ZeroDivisionError: division by zero

Program Explanation

  1. print("Hello") executes successfully and prints Hello.
  2. print(10/0) raises a ZeroDivisionError. The PVM creates a ZeroDivisionError object and searches for handling code, but none is available.
  3. The Python Interpreter terminates the program abnormally and prints the exception information.
  4. 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 ZeroDivisionError is raised by print(10/0).
  • LookupError covers lookup-related errors. Its children IndexError (list index out of range) and KeyError are common.
  • OSError covers operating-system-related errors. Its child FileNotFoundError is raised when a file is missing.

Example - ArithmeticError

🐍Code Cell
1print(10/0)
Output
ZeroDivisionError: division by zero

Example - LookupError

🐍Code Cell
1numbers = [10, 20, 30]
2 
3print(numbers[5])
Output
IndexError: list index out of range

Example - OSError

🐍Code Cell
1open("abc.txt")
Output
FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'

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.

📝 Key Takeaways
  • 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

🧠 Test Your Knowledge

10 Questions
Progress: 0 / 10