intermediatePython Framework • Core Concepts

Errors & Exceptions

Join 1.2k+ learners

Introduction to Errors

Errors fall into two categories: Syntax Errors (parsing issues, like missing colons) and Runtime Errors (exceptions that occur during execution, like dividing by zero). We focus here on handling Runtime Errors.

Python
# Syntax Error (code won't run) # if True print("Hello") # Missing colon # Runtime Error (crashes while running) num = int("abc") # ValueError

Basic Try & Except

Use a try-except block to 'catch' errors and prevent your program from crashing. If an error occurs in the 'try' block, execution jumps immediately to the 'except' block.

Python
try: x = int("not a number") print("This won't print") except ValueError: print("Invalid conversion caught!") print("Program continues...")

Flow of handled error

Start
int('abc')
if
ValueError?
Yes
Print 'Invalid'
Next line
No
Next line
Start/End
Condition
Action

Catching Multiple Exceptions

You can handle different errors differently using multiple except blocks. Code execution enters the first matching block.

Python
try: num = int(input("Enter number: ")) print(10 / num) except ValueError: print("That's not a number!") except ZeroDivisionError: print("Cannot divide by zero!") except Exception as e: print(f"Unknown error: {e}")

Exception Routing

Try
if
ValueError?
Yes
Handle Value
Continue
No
if
ZeroDivision?
Yes
Handle Zero
Continue
No
Continue
Start/End
Condition
Action

Else and Finally

'else' runs if NO exception occurs. 'finally' runs ALWAYS, regardless of errors—perfect for cleanup like closing files.

Python
try: f = open("data.txt") except FileNotFoundError: print("File missing") else: print("File opened!") content = f.read() finally: print("Closing cleanup...") # f.close() if valid

Execution Flow with Finally

Start
Try Block
if
Error?
Yes
Except
Finally (Always)
End
No
Else
Finally (Always)
End
Start/End
Condition
Action

Raising Exceptions

You can intentionally trigger an error using the 'raise' keyword. This is useful for enforcing rules in your functions.

Python
def set_age(age): if age < 0: raise ValueError("Age cannot be negative") print(f"Age set to {age}") try: set_age(-5) except ValueError as e: print(e) # "Age cannot be negative"

Master this concept

Hands-on practice is the fastest way to learn. Head over to our interactive workspace to solve this topic's challenge.

Launch Editor

Visual Lab

Try/Except Flow

Start
Try Block Code
if
Error Occurred?
Yes
Except Block
Continue Execution
No
Continue Execution
Start/End
Condition
Action

New Challenge available!

Master Errors & Exceptions with a hands-on task.