Skip to main content
  1. Notes/
  2. Python ๐Ÿ/

๐Ÿšซ Exception Handling in Python | Lesson 13

Python Progmramming Course
Table of Contents
Python - This article is part of a series.
Part 13: This Article

๐Ÿšซ Exception Handling in Python
#

Mistakes (errors) can happen when your program runs, like dividing by zero or opening a missing file. These errors are called exceptions. Exception handling helps your program handle errors gracefully without crashing, so your app can respond or recover smartly! Letโ€™s learn how to handle exceptions. ๐Ÿ›ก๏ธ


What is an Exception? ๐Ÿค”
#

An exception is an error detected during program execution that interrupts the normal flow of the program.

Example:

print(5 / 0)    # ZeroDivisionError: division by zero

Try and Except Block ๐Ÿงฐ
#

Use try to run code that might cause an error and except to handle the error.

try:
    num = int(input("Enter a number: "))
    result = 10 / num
    print("Result is", result)
except ZeroDivisionError:
    print("Error! You canโ€™t divide by zero.")
except ValueError:
    print("Invalid input! Please enter a valid integer.")

This catches specific errors and lets the program continue.


Catching All Exceptions ๐ŸŒ
#

You can catch any exception (not recommended for all cases but useful sometimes):

try:
    # risky code here
except Exception as e:
    print("An error occurred:", e)

Finally Block ๐Ÿ”„
#

Code inside finally runs no matter what, useful for cleanup (closing files, releasing resources).

try:
    file = open("test.txt", "r")
    data = file.read()
except FileNotFoundError:
    print("File not found!")
finally:
    file.close()
    print("File closed.")

Raising Exceptions ๐Ÿ””
#

You can also raise your own exceptions using raise.

def check_age(age):
    if age < 18:
        raise ValueError("Age must be at least 18.")
    else:
        print("Access granted.")

check_age(15)  # Raises ValueError with message

Practice Questions with Solutions ๐Ÿ†
#

  1. Write a program that asks for a number and prints its square. Use exception handling for invalid inputs.
    • Solution:
try:
    num = int(input("Enter a number: "))
    print("Square:", num * num)
except ValueError:
    print("Please enter a valid integer!")
  1. Write a program to read a file safely using try-except-finally.
  2. Create a function that raises an exception if a string input is empty.

Step-by-Step Mini Project: Safe Division Calculator ๐Ÿงฎ
#

Make a calculator that divides two numbers but handles errors gracefully.

def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return "Error! Cannot divide by zero."
    except TypeError:
        return "Error! Inputs must be numbers."
    
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print("Division result:", safe_divide(num1, num2))

Checklist for This Chapter โœ…
#

  • Used try and except to catch errors
  • Handled specific and general exceptions
  • Used finally for cleanup
  • Raised custom exceptions with raise

Youโ€™re now ready to build robust programs that wonโ€™t crash when things go wrong! Practice catching errors and make your apps user-friendly! ๐Ÿš€

Aryan
Author
Aryan
A little bit about you
Python - This article is part of a series.
Part 13: This Article

Related

โฐ Working with Date and Time in Python | Lesson 16
Python Progmramming Course
๐ŸŽฌ Strings in Python | Lesson 04
Python Progmramming Course
๐Ÿ—๏ธ Object-Oriented Programming (OOP) Concepts in Python | Lesson 15
Python Progmramming Course
๐Ÿ‘ถ Python Basics | Lesson 02
Python Progmramming Course
๐Ÿ“„ File Handling in Python | Lesson 14
Python Progmramming Course
๐Ÿ“‹ Lists in Python | Lesson 05
Python Progmramming Course