CodingNic

Files, Errors, and Automation

Exception Handling

Files, Errors, and Automation 24 min read

Exception Handling

Exception Handling

Sometimes programs crash when something goes wrong.

Examples:

  • Dividing by zero
  • Typing text instead of a number
  • Opening a missing file
  • Using a wrong index

Python calls these problems exceptions.

We can handle them so the program does not crash.

What Is an Exception?

An exception is an error that happens while the program is running.

Without handling it, the program stops.

Why Exception Handling Matters

It helps programs:

  • Keep running
  • Show friendly messages
  • Handle bad input
  • Avoid crashes

Example Without Handling

python
number = int(input("Enter number: "))
print(number)

If the user types:

text
hello

The program crashes.

Using try and except

Use try for risky code.

Use except to handle errors.

python
try:
    number = int(input("Enter number: "))
    print(number)
except:
    print("Please enter a valid number")

Example Output

text
Enter number: hello
Please enter a valid number

Divide by Zero Example

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

Output

text
Cannot divide by zero

File Example

python
try:
    with open("missing.txt") as file:
        print(file.read())
except:
    print("File not found")

Output

text
File not found

Catch Specific Errors

You can catch a specific error type.

python
try:
    number = int("hello")
except ValueError:
    print("That is not a number")

Output

text
That is not a number

Another Example

python
try:
    items = [1, 2]
    print(items[5])
except IndexError:
    print("Index does not exist")

Output

text
Index does not exist

Good Practice

Use clear error messages.

Help the user know what to fix.

Code Along

Build a safe age checker.

Steps:

  • Ask for age
  • Convert to number
  • If invalid input, show message

Mini Challenge

Build a safe calculator.

Steps:

  • Ask for two numbers
  • Add them
  • If user enters bad input, print:
text
Invalid number

Expected output:

text
Enter first number: hi
Invalid number

Real World Use Case

Apps use exception handling for forms, files, payments, APIs, and user input.

Quiz

  1. What is an exception?
  2. What does try do?
  3. What does except do?
  4. Why is exception handling useful?

Assignment

Create a program that asks for a number and prints its double. Handle invalid input safely.

Summary

You learned how to stop crashes and handle errors using try and except in Python.