CodingNic

Error Handling and Debugging

Try and Except Review

Error Handling and Debugging 22 min read

Try and Except Review

Try and Except Review

Sometimes code can fail while running.

Examples:

  • User enters text instead of a number
  • File does not exist
  • Division by zero

Python lets us catch these errors using try and except.

You learned this before. In this lesson, we review it and improve your understanding.

Basic Structure

python
try:
    # risky code
except:
    # run if error happens

Example: Number Input

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

Example Output

text
Enter age: hello
Please enter a valid number

How It Works

  • try runs the code
  • If an error happens, Python jumps to except
  • The program does not crash

Example: Division

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

Output

text
Cannot divide by zero

Example: Missing File

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

Output

text
File not found

Why Use try and except?

They help you:

  • Prevent crashes
  • Show friendly messages
  • Handle bad input
  • Keep programs running

Better Practice

Catch specific errors when possible.

Instead of:

python
except:

Use:

python
except ValueError:

You will learn more in the next lesson.

Code Along

Build a safe double calculator.

Steps:

  • Ask for a number
  • Multiply by 2
  • Handle bad input

Mini Challenge

Build a safe divider.

Steps:

  • Ask for two numbers
  • Divide them
  • If something goes wrong, print:
text
Invalid operation

Expected output:

text
Enter first number: hi
Invalid operation

Real World Use Case

Apps use try and except for forms, login systems, files, payments, and APIs.

Quiz

  1. What does try do?
  2. What does except do?
  3. Why use error handling?
  4. What happens if no error occurs?

Assignment

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

Summary

You reviewed how try and except stop crashes and help programs handle problems safely.