Exception Handling in Python: try–except Explained with Simple Examples

 

What is Exception Handling in Python?

Exception handling in Python is a way to handle runtime errors so that your program does not crash unexpectedly.

In simple words, it allows you to:

  • Detect errors

  • Handle them gracefully

  • Continue running the program

Python uses try–except blocks for exception handling.


Why Exception Handling Is Important

Without exception handling:

  • A single error stops the entire program

  • Users see confusing error messages

With exception handling:

  • Errors are handled properly

  • Programs become user-friendly

  • Applications become stable


Basic Syntax of try–except


try:
    # code that may cause an error
except:
    # code that runs if an error occurs

Example 1: Handling ZeroDivisionError

❌ Without Exception Handling


a = 10
b = 0
print(a / b)

❌ Error:


ZeroDivisionError: division by zero

✔ With try–except


a = 10
b = 0

try:
    print(a / b)
except:
    print("Cannot divide by zero")

✔ Program does not crash
✔ Error handled safely


Example 2: Handling Specific Exceptions

It is a best practice to catch specific errors.

✔ Correct Code


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

✔ Only handles ValueError
✔ Cleaner and safer code


Example 3: Multiple except Blocks


try:
    a = int(input("Enter number: "))
    print(10 / a)
except ValueError:
    print("Please enter a valid number")
except ZeroDivisionError:
    print("Division by zero is not allowed")

✔ Different messages for different errors


Example 4: Using else Block

The else block runs only if no exception occurs.


try:
    num = int("5")
except ValueError:
    print("Error occurred")
else:
    print("Conversion successful:", num)

✔ Clean success handling


Example 5: Using finally Block

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


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

✔ Used for cleanup (closing files, connections)


Example 6: Catching All Exceptions (Not Recommended)


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

⚠ Useful for debugging
⚠ Avoid in production unless necessary


Common Python Exceptions

Exception NameMeaning
TypeErrorWrong data type
ValueErrorInvalid value
NameErrorVariable not defined
IndexErrorInvalid index
KeyErrorInvalid dictionary key
ZeroDivisionErrorDivision by zero

How to Avoid Errors Using try–except

✔ Validate user input
✔ Handle risky operations
✔ Catch specific exceptions
✔ Use finally for cleanup
✔ Avoid silent failures


When NOT to Use try–except

❌ To hide errors
❌ For normal logic flow
❌ Catching all exceptions unnecessarily


Summary

Exception handling in Python helps you control errors instead of letting them crash your program.

Using try–except, you can:

  • Handle errors safely

  • Improve user experience

  • Build reliable applications

Learning exception handling is a must-have skill for every Python developer.


Frequently Asked Questions (FAQ)

Q1: Is try–except mandatory in Python?
No, but strongly recommended.

Q2: Can one try have multiple except blocks?
Yes.

Q3: Does finally always run?
Yes, even if an exception occurs.


📌 Final Tip

Always catch specific exceptions instead of using a general except block.

Comments

Popular posts from this blog

AttributeError in Python: Causes and Fixes with Simple Examples

SyntaxError in Python: Causes and Fixes with Simple Examples

SystemExit in Python: Causes and Fixes with Simple Examples