Exception Handling in Python
• By: [Your Name]
• An overview of how Python manages and
handles runtime errors gracefully using
exception handling.
What is an Exception?
• • An exception is an error detected during
program execution.
• • It disrupts the normal flow of a program.
• • Common examples: ZeroDivisionError,
ValueError, FileNotFoundError.
Why Handle Exceptions?
• • To prevent the program from crashing
unexpectedly.
• • To provide user-friendly error messages.
• • To ensure proper cleanup of resources.
• • To make code more reliable and
maintainable.
Basic Try-Except Structure
• try:
• # Code that may raise an exception
• except ExceptionType:
• # Code to handle the error
• Example:
• try:
• x = 10 / 0
• except ZeroDivisionError:
Multiple Except Blocks
• • You can handle different exceptions
separately:
• try:
• num = int(input('Enter a number: '))
• result = 10 / num
• except ValueError:
• print('Please enter a valid number!')
• except ZeroDivisionError:
Using Else Block
• • The 'else' block runs if no exceptions occur.
• try:
• print('Division successful:', 10 / 2)
• except ZeroDivisionError:
• print('Error occurred!')
• else:
• print('No errors encountered.')
Using Finally Block
• • The 'finally' block always runs — used for
cleanup actions.
• try:
• file = open('[Link]', 'r')
• except FileNotFoundError:
• print('File not found!')
• finally:
• print('Execution finished.')
Raising Exceptions
• • You can raise exceptions manually using
'raise'.
• x = -1
• if x < 0:
• raise ValueError('Value must be positive!')
Common Exception Types
• • ZeroDivisionError – Division by zero.
• • ValueError – Invalid input value.
• • TypeError – Wrong data type used.
• • FileNotFoundError – File not found.
• • IndexError – Index out of range.
Nested Try-Except
• • You can nest try-except blocks for better
control.
• try:
• try:
• num = int(input('Enter number: '))
• print(10 / num)
• except ZeroDivisionError:
• print('Inner: Division by zero')
Best Practices
• • Handle specific exceptions instead of using a
bare 'except'.
• • Keep try blocks short.
• • Use 'finally' to close files or release
resources.
• • Log exceptions for debugging.
Summary
• • Exception handling prevents program
crashes.
• • Use try, except, else, and finally effectively.
• • Raise custom exceptions for better control.
• • Practice writing safe and clean Python code.