Python for Beginners : Exception Handling

Python for Beginners : Exception Handling

What is Exception Handling?

Exception handling refers to the process of detecting and responding to runtime errors. These errors, also known as exceptions, occur when a program encounters an unexpected situation, such as:

  • Dividing a number by zero.
  • Trying to access a file that doesn’t exist.
  • Passing invalid data to a function.

Python provides built-in mechanisms to catch and manage these exceptions, allowing your program to continue running smoothly.

Why Use Exception Handling?

  1. Prevent Crashes: Handle unexpected errors gracefully without halting the program.
  2. Improve User Experience: Provide meaningful error messages.
  3. Debugging: Log specific errors for troubleshooting.

Common Error Types in Python

Here are some frequently encountered exceptions:

Exception Description Example

ZeroDivisionError Raised when dividing by zero. 1 / 0

FileNotFoundError Raised when a file is not found. open('donotexistent.txt', 'r')

ValueError Raised when a function gets an invalid argument. int('Virat')

IndexError Raised when accessing an invalid list index. my_list[10]

KeyError Raised when accessing a non-existent key in a dictionary. my_dict['no']

Using try-except Blocks

A try-except block is used to catch exceptions and handle them gracefully.

Basic Syntax

try:
    # Code that might raise an exception
except ExceptionType:
    # Code to handle the exception        

Example: Handling Division by Zero

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")        

Catching Multiple Exceptions

You can handle multiple exception types in a single block:

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ValueError:
    print("Please enter a valid number!")
except ZeroDivisionError:
    print("Cannot divide by zero!")        

The else Clause

Use the else clause for code that should run only if no exception occurs.

try:
    num = int(input("Enter a number: "))
except ValueError:
    print("That's not a valid number!")
else:
    print(f"The square of the number is {num ** 2}")        

The finally Clause

The finally block contains code that will execute no matter what, often used for cleanup.

try:
    file = open("file.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found!")
finally:
    print("Execution complete!")
    file.close()        

Raising Exceptions

You can use the raise statement to trigger exceptions deliberately.

def check_age(age):
    if age < 18:
        raise ValueError("Age must be 18 or above.")
    print("You are eligible!")

try:
    check_age(15)
except ValueError as e:
    print(e)        

Real-Life Applications of Exception Handling

  • File Operations: Handle missing or corrupted files gracefully.
  • Web Development: Manage invalid inputs or server errors effectively.
  • Data Processing: Handle invalid or missing data points in large datasets.
  • Automation: Log errors during repetitive tasks to avoid disruptions.

Stay tuned as we explore object-oriented programming in Python, covering the basics of classes, objects, and inheritance.

To view or add a comment, sign in

More articles by Mahendar Gajula

Explore content categories