Exception Handling in Python
Presenter: Prof. Assadullah Mohammadi
Exception Handling
Exception handling in Python allows developers to gracefully manage
errors that occur during program execution, rather than letting the
program crash unexpectedly.
Why Use Exception Handling?
• Prevents program crashes.
• Provides user-friendly error messages.
• Helps with debugging and logging.
• Keeps code clean and structured.
Basic Syntax of try-except
Example:
Catching Multiple Exceptions
Catching All Exceptions (not recommended unless necessary)
Using else and finally
Best Practices
• Catch specific exceptions, not generic ones unless necessary.
• Use finally to close files, release resources, or cleanup.
• Don’t use exceptions for flow control (e.g., checking conditions).
• Log exceptions in larger systems instead of just printing them.
list of built-in exceptions in Python
Common Built-in Exceptions
OSError and its Subclasses (for I/O operations)
Arithmetic Exceptions
Lookup Exceptions
Custom Exception Example
You can define your own:
Thank you