Python Exception Handling

Exception Handling

Exception Handling is used to manage runtime errors and prevent programs from crashing.

Exceptions occur when:

  • User enters invalid input
  • File not found
  • Network connection fails
  • Wrong operations (divide by zero)

Basic Structure


Basic Example


Catching Specific Exceptions


Multiple Except Blocks


Using else Block

Runs only when no exception occurs.


Using finally Block

Always runs — even if an error occurs.


Raise an Exception Yourself

Use raise for rules/validation.


Custom Exception


File Handling with Exception


Multiple Exceptions in One Line


Catch All Exceptions


Common Built-in Exceptions

ExceptionWhen it Occurs
ZeroDivisionErrorDivide by zero
ValueErrorWrong data type in conversion
TypeErrorUnsupported operations between types
FileNotFoundErrorFile does not exist
KeyErrorKey not found in dictionary
IndexErrorIndex out of range
NameErrorVariable not defined
ImportErrorModule not found

Real-Time Examples

User Input Validation


Retry File Opening Automatically


API Request Error Handling (Concept)

Leave a Comment