Python Programming
Python Exception Handling
Introduction
While writing programs, errors are unavoidable.
Examples:
- User enters text instead of a number.
- File does not exist.
- Division by zero occurs.
- Wrong variable name is used.
If errors are not handled properly, the program crashes.
Exception Handling allows us to:
- Prevent program crashes
- Display meaningful error messages
- Continue program execution
- Build reliable applications
What is an Error?
An error is a problem that causes a program to behave unexpectedly or stop execution.
Example:
print(10 / 0)
Output:
ZeroDivisionError: division by zero
Types of Errors
Python errors are generally divided into:
1. Syntax Errors
2. Runtime Errors (Exceptions)
3. Logical Errors
Syntax Errors
These occur when Python cannot understand the code.
Example
if True
print("Hello")
Output:
SyntaxError
Correct
if True:
print("Hello")
Runtime Errors (Exceptions)
These occur while the program is running.
Example
number = int("abc")
Output:
ValueError
Python understood the code.
The error happened during execution.
Logical Errors
Program runs successfully but produces wrong results.
Example
length = 10
width = 5
area = length + width
print(area)
Output:
15
Correct answer should be:
50
Program runs but logic is wrong.
What is an Exception?
An exception is a runtime error that interrupts program execution.
Example:
print(10 / 0)
Output:
ZeroDivisionError
Common Python Exceptions
| Exception | Cause |
|---|---|
| ZeroDivisionError | Divide by zero |
| ValueError | Invalid value |
| TypeError | Wrong data type |
| NameError | Variable not found |
| IndexError | Invalid index |
| KeyError | Invalid dictionary key |
| AttributeError | Invalid attribute |
| FileNotFoundError | File not found |
| ImportError | Module import problem |
Python Errors and Exceptions Cheat Sheet
| Error / Exception | Meaning | Example |
|---|---|---|
| SyntaxError | Invalid Python syntax | Missing : |
| IndentationError | Wrong indentation | Misaligned code block |
| TabError | Mixing tabs and spaces | Tabs + spaces together |
| NameError | Variable not defined | print(x) when x doesn't exist |
| TypeError | Invalid operation between data types | "5" + 5 |
| ValueError | Correct type but invalid value | int("abc") |
| ZeroDivisionError | Division by zero | 10 / 0 |
| IndexError | Invalid list/tuple index | mylist[10] |
| KeyError | Dictionary key not found | data["age"] |
| AttributeError | Object doesn't have attribute/method | "abc".append() |
| ImportError | Import failed | Import unavailable object |
| ModuleNotFoundError | Module doesn't exist | import xyz |
| FileNotFoundError | File doesn't exist | open("abc.txt") |
| PermissionError | Permission denied | Writing protected file |
| IsADirectoryError | File operation on directory | open("folder") |
| NotADirectoryError | Directory operation on file | Wrong path usage |
| EOFError | Input unexpectedly ends | input() reaches EOF |
| KeyboardInterrupt | User pressed Ctrl+C | Program interrupted |
| AssertionError | Assertion failed | assert age > 18 |
| RuntimeError | Generic runtime problem | Framework-specific issues |
| RecursionError | Maximum recursion depth reached | Infinite recursion |
| OverflowError | Number too large | Huge math operations |
| MemoryError | Out of memory | Massive data allocation |
| FloatingPointError | Floating-point calculation issue | Rare numerical errors |
| ArithmeticError | Base class for arithmetic errors | Parent exception |
| LookupError | Base class for index/key errors | Parent exception |
| OSError | Operating system related error | File/system problem |
| TimeoutError | Operation timed out | Network timeout |
| ConnectionError | Network connection issue | Server unreachable |
| BrokenPipeError | Writing to closed pipe | IPC/network issue |
| ReferenceError | Weak reference no longer exists | Advanced Python usage |
| StopIteration | Iterator exhausted | next() after end |
| GeneratorExit | Generator closed | Generator cleanup |
| SystemExit | Program exits | sys.exit() |
| UnicodeError | Unicode conversion issue | Encoding/decoding error |
| UnicodeEncodeError | Encoding failed | Unicode → bytes |
| UnicodeDecodeError | Decoding failed | Bytes → Unicode |
| UnicodeTranslateError | Translation failed | Character translation |
| UnboundLocalError | Local variable used before assignment | Global/local confusion |
| BufferError | Buffer operation failed | Memory buffer issues |
| ChildProcessError | Child process problem | Multiprocessing issues |
| InterruptedError | System call interrupted | OS signal interruption |
| ProcessLookupError | Process not found | Invalid PID |
What is Exception Handling?
Exception handling means catching errors and responding gracefully instead of crashing.
Without Exception Handling
num = int(input("Enter Number: "))
result = 100 / num
print(result)
Input:
0
Output:
ZeroDivisionError
Program stops.
With Exception Handling
try:
num = int(input("Enter Number: "))
result = 100 / num
print(result)
except ZeroDivisionError:
print("Cannot divide by zero")
Output:
Cannot divide by zero
Program continues safely.
Try and Except Statement
Syntax
try:
risky code
except ExceptionType:
handling code
Flow Diagram
Try Block
|
|
No Error?
|
Yes
|
Continue
|
|
No
|
Exception Occurs
|
Except Block Executes
Example
try:
number = int(input("Enter Number:"))
print(100 / number)
except ZeroDivisionError:
print("Division by zero is not allowed")
Example: ValueError
try:
age = int(input("Enter Age:"))
except ValueError:
print("Please enter numbers only")
Input:
abc
Output:
Please enter numbers only
Handling Multiple Exceptions
Sometimes multiple exceptions can occur.
Example
try:
number = int(input("Enter Number:"))
result = 100 / number
print(result)
except ValueError:
print("Invalid number")
except ZeroDivisionError:
print("Cannot divide by zero")
Input Examples
Input:
abc
Output:
Invalid number
Input:
0
Output:
Cannot divide by zero
Multiple Exceptions in One Block
Python allows grouping exceptions.
Example
try:
number = int(input("Enter Number:"))
result = 100 / number
except (ValueError, ZeroDivisionError):
print("Invalid Input")
Catching Any Exception
Use:
except Exception:
Example
try:
value = int(input())
print(10 / value)
except Exception:
print("Something went wrong")
⚠ Use carefully.
It can hide useful debugging information.
Exception Object
You can capture the actual error message.
Example
try:
value = int(input())
except Exception as error:
print(error)
Input:
abc
Output:
invalid literal for int()
Example
try:
print(10 / 0)
except Exception as error:
print("Error:", error)
Output:
Error: division by zero
else Block
Runs only when no exception occurs.
Syntax
try:
code
except:
handling
else:
success code
Example
try:
num = int(input())
result = 100 / num
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result =", result)
Input:
5
Output:
Result = 20.0
finally Block
Runs whether an exception occurs or not.
Useful for cleanup operations.
Syntax
try:
code
except:
handling
finally:
cleanup
Example
try:
print(10 / 2)
except ZeroDivisionError:
print("Error")
finally:
print("Finished")
Output:
5.0
Finished
Example with Error
try:
print(10 / 0)
except ZeroDivisionError:
print("Division Error")
finally:
print("Finished")
Output:
Division Error
Finished
Complete Exception Structure
try:
code
except:
handling
else:
success
finally:
cleanup
Visual Flow
Try
|
|--Error?
| |
| Yes
| |
| Except
|
| No
|
Else
|
Finally
Raising Exceptions
Python allows us to generate exceptions manually.
Use:
raise
Example
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
Output:
ValueError: Age cannot be negative
Why Raise Exceptions?
To enforce rules.
Examples:
- Negative age not allowed
- Invalid salary
- Invalid username
- Invalid marks
Writing Your Own Exception
Python allows creating custom exceptions.
Why Create Custom Exceptions?
Built-in exceptions may not fully describe your problem.
Example:
Bank Account Error
Employee Error
Student Error
Inventory Error
Custom exceptions make programs clearer.
Creating Custom Exception
A custom exception must inherit from:
Exception
Example
class InvalidAgeError(Exception):
pass
Custom exception created.
Using Custom Exception
class InvalidAgeError(Exception):
pass
age = -10
if age < 0:
raise InvalidAgeError("Age cannot be negative")
Output:
InvalidAgeError
Example with try-except
class InvalidAgeError(Exception):
pass
try:
age = -5
if age < 0:
raise InvalidAgeError(
"Negative age not allowed"
)
except InvalidAgeError as error:
print(error)
Output:
Negative age not allowed
Bank Example
class InsufficientBalanceError(Exception):
pass
balance = 1000
withdraw = 5000
if withdraw > balance:
raise InsufficientBalanceError(
"Not enough balance"
)
Complete Example
class InsufficientBalanceError(Exception):
pass
try:
balance = 1000
withdraw = 5000
if withdraw > balance:
raise InsufficientBalanceError(
"Insufficient Balance"
)
except InsufficientBalanceError as error:
print(error)
Output:
Insufficient Balance
Common Exception Handling Mistakes
Mistake 1
Using Bare Except
❌ Wrong
try:
value = int(input())
except:
print("Error")
✅ Better
except ValueError:
Mistake 2
Wrong Exception Type
❌ Wrong
try:
print(10 / 0)
except ValueError:
print("Error")
Output:
Program crashes
✅ Correct
except ZeroDivisionError:
Mistake 3
Ignoring Error Message
❌ Bad
except Exception:
pass
Error becomes invisible.
Mistake 4
Putting Too Much Code in try Block
❌ Bad
try:
100 lines of code
except:
Hard to debug.
✅ Better
Keep try block small.
Mistake 5
Forgetting Exception Inheritance
❌ Wrong
class MyError:
pass
✅ Correct
class MyError(Exception):
pass
Best Practices
Catch Specific Exceptions
Good:
except ValueError:
Better than:
except Exception:
Use finally for Cleanup
Example:
finally:
file.close()
Use Custom Exceptions
Useful for:
- Banking
- Inventory
- Employee Management
- Student Systems
Write Meaningful Messages
Good:
raise ValueError(
"Age cannot be negative"
)
Not:
raise ValueError("Error")
Homework 1
Handle division by zero.
Solution
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero")
Homework 2
Handle invalid integer input.
Solution
try:
age = int(input())
except ValueError:
print("Numbers only")
Homework 3
Handle both ValueError and ZeroDivisionError.
Solution
try:
num = int(input())
print(100 / num)
except ValueError:
print("Invalid Number")
except ZeroDivisionError:
print("Cannot divide by zero")
Homework 4
Use else block.
Solution
try:
number = 10
except Exception:
print("Error")
else:
print("Success")
Homework 5
Use finally block.
Solution
try:
print("Working")
finally:
print("Cleanup")
Homework 6
Create InvalidAgeError custom exception.
Solution
class InvalidAgeError(Exception):
pass
try:
age = -1
if age < 0:
raise InvalidAgeError(
"Invalid Age"
)
except InvalidAgeError as error:
print(error)
Homework 7
Create InsufficientBalanceError exception.
Solution
class InsufficientBalanceError(Exception):
pass
try:
balance = 1000
withdraw = 5000
if withdraw > balance:
raise InsufficientBalanceError(
"Balance Too Low"
)
except InsufficientBalanceError as error:
print(error)
Quick Revision
| Topic | Description |
|---|---|
| Error | Problem in program |
| Exception | Runtime error |
| try | Risky code |
| except | Handles exception |
| else | Runs if no exception |
| finally | Always executes |
| raise | Create exception manually |
| Exception | Base exception class |
| Custom Exception | User-defined exception |
Summary
| Concept | Key Point |
|---|---|
| Syntax Error | Code structure problem |
| Runtime Error | Error during execution |
| Logical Error | Wrong output |
| try | Contains risky code |
| except | Catches exceptions |
| else | Executes on success |
| finally | Always executes |
| raise | Creates exception |
| Custom Exception | Inherits from Exception |
| Exception Handling | Prevents program crashes |
Exception Handling That Fixes Problems
Many beginners think exception handling is only for displaying error messages:
try:
risky_code()
except:
print("Error")
However, exception handling can do much more.
Instead of only reporting errors, the except block can:
- Correct invalid data
- Use default values
- Retry operations
- Create missing files
- Reconnect to servers
- Ask for input again
- Recover from failures
Example 1: Fix Invalid User Input
Without Recovery
try:
age = int(input("Enter age: "))
except ValueError:
print("Invalid input")
Improved Version
try:
age = int(input("Enter age: "))
except ValueError:
print("Invalid input.")
age = 18
print("Using default age:", age)
print("Program continues...")
Output
Enter age: abc
Invalid input.
Using default age: 18
Program continues...
Explanation
The exception handler fixed the problem by assigning a default value instead of stopping the program.
Example 2: Automatically Create Missing File
try:
file = open("data.txt", "r")
except FileNotFoundError:
print("File missing. Creating it...")
file = open("data.txt", "w")
file.write("Default Content")
file.close()
file = open("data.txt", "r")
print(file.read())
file.close()
Instead of Crashing
File missing. Creating it...
Default Content
Explanation
The exception handler repaired the issue by creating the missing file automatically.
Example 3: Retry Until Correct Input
while True:
try:
number = int(input("Enter Number: "))
break
except ValueError:
print("Numbers only. Try again.")
print("You entered:", number)
Output
Enter Number: abc
Numbers only. Try again.
Enter Number: xyz
Numbers only. Try again.
Enter Number: 50
You entered: 50
Explanation
This is a common real-world pattern where the program keeps asking for input until the user provides valid data.
Example 4: Recover From Division By Zero
try:
denominator = int(input("Enter divisor: "))
result = 100 / denominator
except ZeroDivisionError:
print("Cannot divide by zero.")
denominator = 1
result = 100 / denominator
print(result)
Output
Enter divisor: 0
Cannot divide by zero.
100.0
Explanation
The exception handler automatically corrected the divisor and allowed the calculation to continue.
Example 5: Dictionary Recovery
student = {
"name": "John"
}
try:
age = student["age"]
except KeyError:
print("Age not found.")
student["age"] = 18
age = student["age"]
print(age)
Output
Age not found.
18
Explanation
The exception handler repaired the data structure by creating the missing key.
Real-World Rule
A professional developer usually follows this principle:
Try to PREVENT errors first.
If prevention is impossible,
use exceptions to RECOVER.
Only show error messages
when recovery isn't possible.
Good Exception Handling
Error Occurs
↓
Detect Error
↓
Fix Problem
↓
Continue Program
Poor Exception Handling
Error Occurs
↓
Print Error
↓
Crash
Key Takeaway
The difference between beginner and professional exception handling is:
| Beginner Approach | Professional Approach |
|---|---|
| Catch error | Catch error |
| Print message | Analyze error |
| Stop execution | Fix problem if possible |
| Program may fail | Program continues safely |
Professional software often uses exceptions not just to detect problems, but to recover from them and keep the application running smoothly.
Before moving to the next chapter, make sure you can:
✅ Explain different types of errors
✅ Use try and except correctly
✅ Handle multiple exceptions
✅ Use else and finally
✅ Raise exceptions manually
✅ Create your own custom exceptions
✅ Build safe and reliable Python programs