PythonException Handling
try-except And Exceptional Hierarchy
Exception Handling Syntax
Python uses try–except blocks to handle runtime exceptions and prevent application crashes.
Basic try–except Syntax
try:
# risky code
except ErrorType:
# handling code- Code inside
tryis monitored for errors - If an exception occurs, Python jumps to the matching
exceptblock
Example: Handling Division by Zero
a = 5
b = 0
try:
result = a / b
print("Result is:", result)
except Exception:
print("An error occurred: Division by zero is not allowed")
print("End of execution")Output
An error occurred: Division by zero is not allowed
End of execution- Application does not crash
- Remaining code executes normally
Handling Multiple Exceptions
Different errors require different handling logic.
Example
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
result = a / b
print("Result is:", result)
except ZeroDivisionError as zde:
print("Division by zero is not allowed.", zde)
except ValueError as ve:
print("Invalid input. Please enter numeric values.", ve)
except Exception as e:
print("An unexpected error occurred.", e)
print("End of execution")Sample Outputs
Case 1: Zero Division
Enter numerator: 4
Enter denominator: 0
Division by zero is not allowed. division by zero
End of executionCase 2: Invalid Input
Enter numerator: 4
Enter denominator: t
Invalid input. Please enter numeric values. invalid literal for int()
End of execution
Python Exception Hierarchy
Python exceptions follow a hierarchical structure.
Exception Hierarchy Diagram
BaseException
│
├── SystemExit
├── KeyboardInterrupt
│
└── Exception
├── ArithmeticError
│ └── ZeroDivisionError
├── ValueError
├── TypeError
├── IndexError
└── FileNotFoundErrorWhy Hierarchy Matters?
- Parent exceptions catch child exceptions
- Use specific exceptions first
- Use generic
Exceptionas a fallback
Summary
- Python uses
try–exceptblocks to handle runtime exceptions and prevent application crashes. - Code inside the
tryblock is monitored, and matchingexceptblocks handle specific errors. - Multiple
exceptblocks allow handling different exception types with customized messages. - Python exceptions follow a hierarchical structure, where parent exceptions can catch child exceptions.
- Always handle specific exceptions first and use
Exceptionas a fallback for unexpected errors.
Written By: Muskan Garg
How is this guide?
Last updated on
