Exception Handling | Dataplexa

Exception Handling in Python

In programming, errors can happen when your program runs. These errors crash the program unless we handle them properly. Python provides a powerful system called Exception Handling to manage errors and continue program execution smoothly.

Exception handling is extremely important in real-world applications because it helps prevent program crashes, protects user data, and allows you to give meaningful error messages.

What Is an Exception?

An exception is an error that occurs while the program is running. For example:

  • Dividing a number by zero
  • Trying to open a file that does not exist
  • Using a variable that is not defined
  • Incorrect data types

If exceptions are not handled, the program stops immediately. But with exception handling, we can **catch** the error and keep the program running.

The try and except Block

Python uses a simple structure:

try:
    # Code that might cause an error
except:
    # Code to run if an error occurs

Basic Example

Here’s a simple example of handling division by zero:

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

Output: "Error: Cannot divide by zero!"

Handling Specific Exceptions

Instead of catching all errors, you can handle specific types of exceptions such as:

  • ZeroDivisionError
  • ValueError
  • FileNotFoundError
  • TypeError

Example:

try:
    num = int("abc")
except ValueError:
    print("Error: Invalid number format!")

Multiple Except Blocks

You can handle multiple exceptions separately.

try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
except TypeError:
    print("Type error occurred!")

The else Block

The else block runs only when no exception occurs.

try:
    x = 10 / 2
except ZeroDivisionError:
    print("Division error!")
else:
    print("Division successful:", x)

The finally Block

The finally block always runs — whether an exception occurs or not. It is often used for cleanup operations like closing files or database connections.

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

Try–Except–Else–Finally (Full Structure)

try:
    number = int(input("Enter a number: "))
except ValueError:
    print("Invalid input!")
else:
    print("You entered:", number)
finally:
    print("Thank you for using the program!")

Raising Your Own Exceptions

Sometimes you want to manually raise an exception using raise.

age = -5

if age < 0:
    raise ValueError("Age cannot be negative")

Manually raising exceptions helps validate data in real projects.

Real-World Example: Safe User Input

while True:
    try:
        value = int(input("Enter a valid age: "))
        print("Age saved:", value)
        break
    except ValueError:
        print("Invalid input. Please enter numbers only.")

📝 Practice Exercises


Exercise 1

Write a program that takes two numbers and handles division errors.

Exercise 2

Ask the user for a filename. Handle case where the file does not exist.

Exercise 3

Convert user input to integer. Use try–except to avoid crashing.

Exercise 4

Use finally to print “Program ended” whether an error happens or not.


✅ Practice Answers


Answer 1

try:
    a = int(input("Enter number 1: "))
    b = int(input("Enter number 2: "))
    print("Result:", a / b)
except ZeroDivisionError:
    print("Cannot divide by zero!")

Answer 2

try:
    filename = input("Enter filename: ")
    file = open(filename, "r")
    print(file.read())
except FileNotFoundError:
    print("File does not exist!")

Answer 3

try:
    number = int(input("Enter a number: "))
    print("Valid number:", number)
except ValueError:
    print("Please enter a valid integer!")

Answer 4

try:
    value = int(input("Enter something: "))
    print("You entered:", value)
except:
    print("An error occurred!")
finally:
    print("Program ended")