Skip to content

Latest commit

 

History

History
358 lines (230 loc) · 5.67 KB

File metadata and controls

358 lines (230 loc) · 5.67 KB

Lesson 5: Exceptions (Error Handling)

Back to the main roadmap | Previous lesson: Type Casting | Next lesson: Functions & Built-in Functions

What is an Exception?

An exception is an error that occurs while your program is running.

When Python encounters something it cannot do, it stops the program and displays an error message.

For example:

age = int("abc")

Output

ValueError: invalid literal for int() with base 10: 'abc'

Python stops executing the program at that point.


Why Handle Exceptions?

Imagine you're building a calculator.

If the user accidentally types:

abc

instead of a number, you probably don't want your entire program to crash.

Instead, you want to display a friendly message like:

That isn't a valid number. Please try again.

Exception handling lets your program recover from errors instead of crashing.


The try and except Blocks

The basic way to handle errors is with try and except.

Example

try:
    age = int(input("Enter your age: "))
    print("Next year you'll be", age + 1)
except:
    print("That wasn't a valid number!")

Sample Input

abc

Output

That wasn't a valid number!

How It Works

  • try → Execute this code.
  • If everything works, Python skips the except block.
  • If an error occurs, Python immediately jumps to the matching except block.
  • The program continues running instead of crashing.

Think of try as a safety net.


Catching Specific Exceptions

Using only except: catches every type of error.

A better approach is to catch the exact error you expect.

Example

try:
    age = int(input("Enter your age: "))
except ValueError:
    print("That's not a number!")

This only catches a ValueError.


Common Python Exceptions

Exception When It Happens Example
ValueError Right type, wrong value int("abc")
TypeError Mixing incompatible types "5" + 5
ZeroDivisionError Dividing by zero 10 / 0
IndexError Invalid list index numbers[99]
KeyError Dictionary key doesn't exist student["age"]
FileNotFoundError File cannot be found open("ghost.txt")

Handling Multiple Exceptions

You can catch different errors separately.

Example

try:
    number = int(input("Enter a number: "))
    result = 10 / number
    print(result)

except ValueError:
    print("That wasn't a number!")

except ZeroDivisionError:
    print("You can't divide by zero!")

Python checks each except block in order and executes the one that matches the error.


The else Block

The else block runs only if no exception occurs.

Example

try:
    number = int(input("Enter a number: "))

except ValueError:
    print("Not a number!")

else:
    print("Great! You entered", number)

Sample Input

15

Output

Great! You entered 15

The finally Block

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

Example

try:
    number = int(input("Enter a number: "))

except ValueError:
    print("Not a number!")

finally:
    print("This always runs.")

Output (Input: abc)

Not a number!
This always runs.

finally is commonly used for cleanup tasks such as:

  • Closing files
  • Closing database connections
  • Releasing resources

Getting the Error Message

Sometimes you want to know exactly what went wrong.

Use as to store the error in a variable.

Example

try:
    number = 10 / 0

except ZeroDivisionError as e:
    print("Error occurred:", e)

Output

Error occurred: division by zero

Here, e contains the error message generated by Python.


Raising Your Own Exceptions

You can create your own exceptions using the raise keyword.

Example

age = -5

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

Output

ValueError: Age cannot be negative!

This is useful when you want to prevent invalid data from being used in your program.


Practice Program

Create a file named lesson5.py.

def get_age():
    try:
        age = int(input("Enter your age: "))

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

    except ValueError as e:
        print("Invalid input:", e)
        return None

    else:
        print("Thanks! You entered a valid age.")
        return age

    finally:
        print("Done trying to get age.\n")


result = get_age()

print("Final result:", result)

Try These Inputs

Case 1

Input

25

Output

Thanks! You entered a valid age.
Done trying to get age.

Final result: 25

Case 2

Input

abc

Output

Invalid input: invalid literal for int() with base 10: 'abc'
Done trying to get age.

Final result: None

Case 3

Input

-5

Output

Invalid input: Age cannot be negative!
Done trying to get age.

Final result: None

Key Takeaways

  • Exceptions are runtime errors.
  • try contains code that might fail.
  • except handles errors without crashing the program.
  • Catch specific exceptions whenever possible.
  • else runs only when no exception occurs.
  • finally always runs.
  • raise lets you create your own exceptions.
  • as lets you access the actual error message.

Back to the main roadmap | Previous lesson: Type Casting | Next lesson: Functions & Built-in Functions