Error and Exception Handling
Learn how to handle mistakes and crashes gracefully in your code
Learning Objectives
- Understand the difference between Syntax Errors and Exceptions
- Use try and except blocks to handle errors
- Use the finally block for cleanup tasks
- Prevent your program from crashing on unexpected input
When things go wrong
No matter how good a programmer you are, things will go wrong. A user might enter a string when you expected a number, or your code might try to open a file that doesn’t exist.
Without error handling, your program will “crash” (stop immediately and show an ugly error message). Today, we learn how to handle these mistakes gracefully.
Syntax Errors vs. Exceptions
- Syntax Errors: These are “typos” in your code. Python won’t even start running the program. (e.g., forgetting a colon).
- Exceptions: These occur while the program is running. The code is valid, but an operation failed. (e.g., dividing by zero).
The try...except Block
In Python, we handle exceptions using the try and except keywords.
|
|
How it works:
- Python tries to run the code in the
tryblock. - If an error occurs, it jumps to the
exceptblock that matches that error type. - If no error occurs, the
exceptblocks are skipped.
The finally Block
The finally block runs no matter what, whether an error occurred or not. It is typically used for “cleanup” (like closing a database connection).
|
|
Handling “Any” Error
If you don’t know exactly what error might happen, you can use a generic except:
|
|
Interactive Practice
Imagine a calculator app. If a user tries to divide by zero, instead of crashing, the app should show a friendly “Oops!” message.
Quiz
Complete this quiz with a minimum score of 80% to mark Day 12 as complete.
Discussion
Have questions or want to discuss this lesson? Join the conversation below!