Skip to main content

Command Palette

Search for a command to run...

Python Basics — Day 14 Exception Handling (try / except)

Updated
2 min read
S

Aspiring Full-Stack Developer | Python · Django · React · SQL | documenting my learning journey

Building skills in Python and full-stack development, with a focus on web apps and system design

Junior developer in training — Python, Django, React — preparing for a career in full-stack engineering

From Python basics to full-stack projects, sharing my progress as I grow into a developer

Future full-stack engineer | Learning in public: Python, APIs, Databases, and Web Development

01. What is an Error (Exception)?

  • An error occurs when something goes wrong during execution → program stops.

  • Examples: dividing by zero, invalid index access, missing file.

print(10 / 0)   # ZeroDivisionError
numbers = [1, 2, 3]
print(numbers[5])   # IndexError

02. Basic try / except Structure

try:
    # Code to execute
except:
    # Code to run if an error occurs

Example:

try:
    x = int(input("Enter a number: "))
    print("You entered:", x)
except:
    print("That is not a number!")

03. Handling Specific Exceptions

You can handle different types of exceptions separately.

try:
    num = int("abc")   # Raises ValueError
except ValueError:
    print("Cannot convert to integer.")

04. Handling Multiple Exceptions

try:
    a = [1, 2, 3]
    print(a[5])         # IndexError
    print(10 / 0)       # ZeroDivisionError
except IndexError:
    print("List index out of range!")
except ZeroDivisionError:
    print("Cannot divide by zero.")

05. Using else and finally

  • else → runs only if no exception occurs

  • finally → always runs, whether an exception occurs or not

try:
    n = int(input("Enter a number: "))
except ValueError:
    print("Invalid input.")
else:
    print("Valid number:", n)
finally:
    print("Program finished.")

06. Using Exception Objects

try:
    x = 10 / 0
except Exception as e:
    print("Error occurred:", e)

07. Practice Examples

Example 1: Prevent Division by Zero

try:
    a = int(input("Enter numerator: "))
    b = int(input("Enter denominator: "))
    print(a / b)
except ZeroDivisionError:
    print("Cannot divide by zero.")

Example 2: File Reading

try:
    with open("not_exist.txt", "r", encoding="utf-8") as f:
        data = f.read()
except FileNotFoundError:
    print("File not found!")

Python Basics

Part 14 of 21

A collection of study notes from my university and self-learning journey. This series covers Python fundamentals step by step — from setup to core concepts — to help both myself and others build a solid foundation in coding.

Up next

Python Basics — Day 15 Functions Basics (def, return, parameters)

01. What is a Function? A block of code that performs a specific task Defined with def, and executed when called def say_hello(): print("Hello!") say_hello() # Call the function 02. Parameters You can pass values into functions as parame...

More from this blog

S

Sabin’s DevLog

21 posts

I plan to upload everything I study and prepare here. I hope it can be helpful to others, and I also want my future self to see the learning journey I’ve been through.