
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Handle Python Exception Inside If Statement
You cannot directly use an if statement to catch exceptions in Python. Instead, use a try-except block and place if conditions inside the except to respond differently based on the type or message of the exception. This allows you to write conditional logic for exception handling.
Using if Inside the except Block
You can write if conditions inside the except block to check the type or details of the exception and take appropriate action.
Example: Matching Exception Message with "if"
In this example, we catch a ValueError and use if statement to inspect its message -
def process_input(value): try: number = int(value) print("Number is:", number) except ValueError as e: if "invalid literal" in str(e): print("Cannot convert input to integer.") else: print("Some other value error occurred.") process_input("abc")
Here, the if inside except filters the exception message to customize the output -
Cannot convert input to integer.
Example: Using "if isinstance" to Check Error Type
In this example, we catch all exceptions and use if isinstance to identify the type -
def divide(a, b): try: return a / b except Exception as e: if isinstance(e, ZeroDivisionError): print("Cannot divide by zero.") elif isinstance(e, TypeError): print("Invalid input types.") else: print("Other error:", e) divide(5, 0) divide("5", 2)
The reult produced is as follows -
Cannot divide by zero. Invalid input types.
This approach helps you to handle multiple exception types using a single except block combined with if conditions.
Incorrect Way: Using "if" to Catch Exceptions
Using if alone cannot catch exceptions. Python will raise the error before the if statement is even checked.
Example
Here, the exception occurs while converting the value to an integer, before the if condition can be evaluated -
# This will not work and will raise an exception value = "abc" if int(value): # ValueError occurs here before 'if' runs print("Valid")
The error obtained is as shown below -
ValueError: invalid literal for int() with base 10: 'abc'