Exception Handling in Python

What is an Exception?

An exception is an error that occurs during the execution of a program and stops the normal flow of the program.

Example of an Exception

print(10 / 0)

This causes a ZeroDivisionError because a number cannot be divided by zero.

Article Algo

What is Exception Handling?

Exception handling in Python is a way to handle runtime errors so that the program does not crash and can continue running smoothly.

Python handles exceptions using:

  • try
  • except
  • else
  • finally

Article Algo

1. try and except

The try block contains code that may cause an error. The except block handles the error if it occurs.

Example

try: x = 10 / 0 print(x) except: print("Error: Cannot divide by zero")

Explanation

  • Python tries to execute the code inside try.
  • 10 / 0 causes an error.
  • Instead of crashing, control goes to the except block.
  • The error message is printed safely.

Article Algo

2. Handling Specific Exceptions

We can handle specific types of errors.

Example

try: num = int("abc") except ValueError: print("ValueError: Invalid number")

Explanation

  • "abc" cannot be converted to an integer.
  • Python raises a ValueError.
  • The matching except ValueError block handles it.
  • This makes error handling more accurate.

Article Algo

3. try with else

The else block runs only if no exception occurs.

Example

try: a = 10 b = 2 print(a / b) except ZeroDivisionError: print("Cannot divide by zero") else: print("Division successful")

Explanation

  • No error occurs in the try block.
  • The except block is skipped.
  • The else block executes successfully.

Article Algo

4. finally Block

The finally block always executes, whether an exception occurs or not.

Example

try: file = open("data.txt", "r") print(file.read()) except: print("File not found") finally: print("Program finished")

Explanation

  • Python tries to open the file.
  • If the file exists, it reads it.
  • If not, an error message is printed.
  • The finally block runs in all cases.

Article Algo

5. Raising an Exception

We can manually raise an exception using the raise keyword.

Example

age = -5 if age < 0: raise ValueError("Age cannot be negative")

Explanation

  • The condition checks if age is negative.
  • raise forces a ValueError.
  • This is useful for validating input.

Article Algo

Common Built-in Exceptions

  • ZeroDivisionError → Division by zero
  • ValueError → Invalid value
  • TypeError → Wrong data type
  • IndexError → Index out of range
  • KeyError → Missing dictionary key

Article Algo