About Lesson
๐ฏ Learning Objectives
By the end of this lesson, learners will be able to:
-
Understand what exceptions are
-
Use
try
andexcept
to catch and handle errors -
Handle specific exceptions like
ZeroDivisionError
,ValueError
, etc. -
Use
else
andfinally
blocks for complete error management -
Prevent crashes and build reliable programs
๐ Lesson Content
๐น What is an Exception?
An exception is an error that occurs during program execution.
If not handled, it will stop the program.
Example of an unhandled exception:
๐ธ Basic Try-Except Syntax
โ This prevents the program from crashing when an error happens.
๐ธ Example: Handling Division by Zero
๐ธ Handling Multiple Specific Exceptions
๐ธ Using else
and finally
Block | Purpose |
---|---|
try |
Code that might cause an exception |
except |
Executes when an exception occurs |
else |
Executes if no error occurs |
finally |
Executes always, useful for cleanup like file.close() |
ย
๐ Real-World Example: File Handling with Error Catching
โ ๏ธ Common Mistakes
Mistake | Why It’s Wrong |
---|---|
Catching all exceptions blindly | Hides useful error details |
Using except: without specifying |
Should be avoided unless absolutely necessary |
Not using finally for cleanups |
Risk of open resources (e.g., open files) |
ย
๐ Assignment
Write a program that:
-
Asks the user to input two numbers
-
Tries to divide them
-
Catches
ZeroDivisionError
andValueError
-
Uses
finally
to print"Operation complete."