Python Mastery – From Basics to Brilliance / Exception Handling

Try-Except Blocks

✅ What is Exception Handling?

It’s the process of catching and handling runtime errors in a graceful manner to avoid crashing the program.

🔧 Syntax:

try:
    # risky code
except SomeError:
    # handle error

💡 Example:

try:
    number = int(input("Enter a number: "))
    print("You entered:", number)
except ValueError:
    print("Oops! Please enter a valid number.")

✅ Helps to gracefully deal with situations that may crash your program.

Output -1 (Valid Input)

Enter a number: 42
You entered: 42

Output - 2(Invalid Input)

Enter a number: hello
Oops! Please enter a valid number.

✅The else block

🏠 Real-life Analogy:

You try to turn on a fan (try). If the power is off (except), you handle it.

If everything is fine, you relax and enjoy (else).


✅ Python Example:

try:
    result = 10 / 2
except ZeroDivisionError:
    print("You can’t divide by zero.")
else:
    print("Everything went fine! Result is:", result)
Everything went fine! Result is: 5.0

✅ Why use else?

To run something only if no error occurred.

It keeps your code neat — you don’t mix “success” code inside try or except.


🔹 finally Clause — Explained Simply

💬 What does it do?

The finally block runs no matter what — even if there’s an error or not.

🧼 Real-life Analogy:

You’re cooking (try), and something might go wrong (like spilling).

Whether it goes well or not, you still clean the kitchen (finally).

✅ Python Example:

try:
    f = open("data.txt", "r")  # Trying to open a file
except FileNotFoundError:
    print("File not found.")
finally:
    print("Closing everything... Done.")
# 🖨️ Output if file does not exist:
File not found.
Closing everything... Done.
# 🖨️ Output if file exists:
Closing everything... Done.

🔍 Why Use Try-Except?

  • Prevents your app from crashing.

  • Gives clear feedback to users.

  • Maintains smooth user experience.

✅ Why use finally?

  • To clean up (like closing files, releasing memory, disconnecting a server)

  • It ensures that certain code always runs, even if something goes wrong