Lesson 6.3: Exception Handling – try, except, finally
Introduction:
Exceptions are errors that occur during program execution. Exception handling allows a program to continue running even when an error occurs, making programs more robust and user-friendly. Python uses try, except, and finally blocks for handling exceptions.
1. Basic try-except:
-
Wrap code that may cause an error in a
tryblock. -
Handle the error in the
exceptblock.
Example:
Explanation:
-
If the user enters
0,ZeroDivisionErroris handled. -
If the user enters a non-integer,
ValueErroris handled.
2. Using else Block:
-
Executes if no exception occurs in the
tryblock.
3. Using finally Block:
-
Executes always, regardless of whether an exception occurred or not.
-
Useful for cleanup actions like closing files.
4. Catching Multiple Exceptions:
Practical Tips:
-
Always catch specific exceptions rather than using a general
except: -
Use
finallyfor cleanup tasks like closing files or releasing resources -
Use
elsefor code that should run only if no exception occurs
Learning Outcome of This Lesson:
-
Understand what exceptions are and why they occur
-
Use
try,except,else, andfinallyto handle errors -
Write robust code that can handle runtime errors gracefully
-
Apply exception handling in real-world programs for better reliability
