Coding/Learn/python/error handling
Python Beginner Course
01.Introduction to Python
02.Your First Python Program
03.Syntax & Indentation
04.Comments & Documentation
05.Variables
06.Core Data Types
07.Numbers & Arithmetic Operators
08.Text & Strings in Depth
09.Boolean Logic
10.Type Conversion & Casting
11.Interactive User Input
12.Assignment & Shorthand Operators
13.Comparison Operators
14.Logical Operators (and, or, not)
15.If Statements & Conditional Execution
16.If-Else Branching (Dual Paths)
17.If-Elif-Else (Multi-Path Decisions)
18.While Loops & Iteration
19.For Loops & Sequence Traversal
20.The range() Function
21.Lists & Mutable Sequences
22.Tuples & Immutable Data
23.Sets & Unique Collections
24.Dictionaries & Key-Value Stores
25.List Indexing & Slicing
26.Essential List Methods
27.Essential String Methods
28.Functions & Modular Code
29.Function Parameters & Arguments
30.Return Values & Data Flow
31.Exception Handling (try / except)
32.Capstone Mini-Projects
Course Certificate0%

Complete all lessons to earn

LearnException Handling (try / except)
31 / 32 0%
Lesson 31 of 32
8 mins read

Exception Handling (try / except)

PreviousNext Lesson
In Plain English

In the real world, things go wrong: users type words when you asked for numbers, servers drop connections, or files go missing. Without error handling, your program crashes with an ugly traceback. With try / except, your code catches errors and recovers gracefully.

The Mental Model

"try/except is the digital safety net under a tightrope walker. If the program slips (an error occurs), the safety net catches it, dusts it off, and allows the show to go on without crashing into the ground."

Deep Dive: How It Works

The try block contains risky code that might cause an exception (like converting user input with int() or dividing by a variable).

The except block only executes if an error occurs inside the try block. You can catch specific error types (e.g. except ValueError:, except ZeroDivisionError:).

The else block (optional) runs only if NO error occurred in the try block.

The finally block (optional) ALWAYS runs no matter what (even if an error occurred), which is great for closing open files or database connections.

Syntax Blueprint

try:
    number = int(user_input)
    result = 100 / number
except ValueError:
    print("Please enter digits only!")
except ZeroDivisionError:
    print("Cannot divide by zero!")

Wrap risky code in try, and handle specific error types in except blocks.

PointCore Rules to Remember

Point star
Prevents Crashes: Programs handle invalid inputs gracefully instead of crashing abruptly.
Point star
Catch Specific Errors: Always catch specific exceptions (ValueError, ZeroDivisionError) rather than a bare except:.
Point star
The finally Block: Code in finally: always executes, making it ideal for cleanup actions.

Common Beginner Traps & How to Fix Them

Mistake:Using a bare except: with no error type

Why it happens: A bare except catches everything, including KeyboardInterrupt (Ctrl+C), making your script impossible to cancel.

How to fix: Catch specific errors: except ValueError: or except Exception as e:.

Pro Tip: You can inspect the exact error message using "as": except ValueError as error: print(f"Details: {error}").

Live Interactive Example

Hit Run Code to see it live
Graceful Error Recovery with try/except
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
Output Console
Click "Run Code" to view the rendered output.
How it works: Each error was caught by its respective except block, allowing the loop to continue processing smoothly.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Catch a ZeroDivisionError

  • PointWrap 10 / 0 inside a try block.
  • PointIn the except ZeroDivisionError: block, print "Cannot divide by zero".
1
2
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates