What is Exception Handling in Python? Definition, syntax, and example with questions.
As we know, when code is in production, a single error can bring down the entire website or cause it to crash. To prevent this, all dynamic code should be written with exception handling.
Exception handling is a way to handle errors gracefully.
Python uses try, except, else, and finally blocks to manage exceptions.
Syntax:
try:
# Code that might have doubt raise an error
except Exception:
# run only when an error comes
else:
# Code that runs if no error occurs
finally:
# Code that always runs
Example:
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
except Exception:
print("Error commes..")
else:
print(f"The result of division is {result}.")
finally:
print("Execution complete.")
Output:
Enter a number: 10
Enter another number: 2
The result of division is 5.0.
Execution complete.
if i pass:
Output:
Enter a number: 10
Enter another number: 0
Error commes..
Execution complete.
Now, There are multiple ways to handle these errors:
Binds the exception/error usign e, By doing this we get standard errors.
Example:
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
except Exception as e:
print(e)
else:
print(f"The result of division is {result}.")
finally:
print("Execution complete.")
Output:
Enter a number: 10
Enter another number: 0
division by zero
Execution complete.
Every type of error has its own exception name. In Python, there are many exceptions, like IndexError, Syntaxerror, Valueerror, TypeError, and many more. Click here to check.
You can handle errors with their respective exception.
For Example:
Example:
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
except ValueError:
print("Please enter a valid integer.")
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print(f"The result of division is {result}.")
finally:
print("Execution complete.")
Output:
Enter a number: hey
Please enter a valid integer.
Execution complete.
Output:
Enter a number: 10
Enter another number: 0
Cannot divide by zero.
Execution complete.
Output:
Enter a number: 12
Enter another number: 3
The result of division is 4.0.
Execution complete.
20+ unique Python exception-handling interview questions with answers and examples
Question 1. What is the purpose of using try-except in Python?
Answer: The try-except block in Python is used to handle runtime errors, allowing the program to continue execution even if an error occurs in the try block.
Example:
try:
result = 5 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
Output:
Cannot divide by zero.
Question 2. What does the else block do in a try-except structure?
Answer: The else block runs only if no exception is raised in the try block.
Example:
try:
result = 10 / 2
except ZeroDivisionError:
print("Division by zero!")
else:
print("Division successful:", result)
Output:
Division successful: 5.0
Question 3. Can we have multiple except blocks for a single try? Why would this be useful?
Answer: Yes, multiple except blocks allow handling of specific exceptions differently.
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Input must be an integer.")
except ZeroDivisionError:
print("Cannot divide by zero.")
Output:
Enter a number: eeee
Input must be an integer.
Question 4. Explain the finally block. When is it executed?
Answer: The finally block executes after the try and except blocks, regardless of whether an exception occurred.
Example:
try:
file = open("data.txt", "r")
except FileNotFoundError:
print("File not found.")
finally:
print("This runs no matter what.")
Output:
File not found.
This runs no matter what.
Question 5. What is an exception hierarchy? Why is it important?
Answer: Exception hierarchy refers to the structure where all exception classes inherit from the base Exception class. It’s important to handle specific exceptions before general ones to avoid missing specific errors.
Example:
try:
result = 5 / 0
except ZeroDivisionError:
print("Handle zero division error")
except Exception:
print("Handle general exception")
Output:
Handle zero division error
Question 6. What does raise do in exception handling?
Answer: The raise keyword manually triggers an exception, allowing the programmer to signal an error in specific situations.
Example:
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or older.")
try:
check_age(16)
except ValueError as e:
print(e)
Output:
Age must be 18 or older.
Question 7. Can you have an else block without an except?
Answer: No, an else block must follow a try-except structure.
Example:
try:
print("Hello")
else:
print("Else without except")
Output:
File "<main.py>", line 3
else:
^^^^
SyntaxError: expected 'except' or 'finally' block
Question 8. How would you log exceptions instead of printing them?
Answer: Use the logging module to log exceptions for better traceability in production.
Example:
import logging
logging.basicConfig(level=logging.ERROR)
try:
result = 5 / 0
except ZeroDivisionError as e:
logging.error("An error occurred", exc_info=True)
Output:
ZeroDivisionError: division by zero
Question 9. What is the purpose of exc_info=True in the logging module?
Answer: It includes the traceback information in the log, helping with debugging.
Example:
import logging
logging.error("An error occurred", exc_info=True)
Output:
ERROR:root:An error occurred
NoneType: None
Question 10. What happens if both finally and except blocks return a value?
Answer: If finally returns a value, it overrides the except return value.
Example:
def test():
try:
return "try"
except:
return "except"
finally:
return "finally"
print(test())
Output:
finally
Question 11. How can you create a custom exception?
Answer: Create a custom exception by subclassing Exception.
Example:
class CustomError(Exception):
pass
raise CustomError("This is a custom error.")
Output:
CustomError: This is a custom error.
Question 12. Can exceptions be caught within the same block they were raised?
Answer: No, exceptions propagate to the nearest enclosing try-except block.
Example:
try:
raise ValueError("Example error")
except ValueError:
print("Caught the error.")
Output:
Caught the error.
Question 13. What is exception chaining, and when is it used?
Answer: Exception chaining (using raise ... from) links a new exception to an original one for detailed traceback.
Example:
try:
raise ValueError("Initial error")
except ValueError as e:
raise TypeError("New error") from e
Output:
ValueError: Initial error
The above exception was the direct cause of the following exception:
TypeError: New error
Question 14. How does the with statement relate to exception handling?
Answer: The with statement simplifies resource management, handling exceptions in cleanup.
Example:
with open("file.txt", "w") as file:
file.write("Hello")
Output:
PermissionError: [Errno 13] Permission denied: 'file.txt'
Question 15. Can you catch multiple exceptions in a single except?
Answer: Yes, by using a tuple of exceptions.
Example:
try:
result = 10 / "a"
except (ZeroDivisionError, TypeError) as e:
print("Caught an exception:", e)
Output:
Caught an exception: unsupported operand type(s) for /: 'int' and 'str'
Question 16. What is the purpose of assert in exception handling?
Answer: assert checks conditions; it raises an AssertionError if the condition is False.
Example:
x = 5
assert x > 10, "x is too small"
Output:
AssertionError: x is too small
Question 17. How can you retrieve the traceback of an exception?
Answer: Use traceback module to get traceback information.
Example:
import traceback
try:
1 / 0
except ZeroDivisionError:
print(traceback.format_exc())
Output:
ZeroDivisionError: division by zero
Question 18. What’s the difference between Exception and BaseException?
Answer: BaseException is the root of all exceptions, while Exception is for common errors.
Example:
try:
raise KeyboardInterrupt
except BaseException:
print("Caught KeyboardInterrupt")
Output:
Caught KeyboardInterrupt
Question 19. Explain the role of sys.exc_info() in exception handling.
Answer: sys.exc_info() retrieves the exception type, value, and traceback.
Example:
import sys
try:
1 / 0
except ZeroDivisionError:
print(sys.exc_info())
Output:
A module you have imported isn't available at the moment. It will be available soon.
Question 20. How does exception handling impact program performance?
Answer: Exception handling can be costly in terms of performance if misused, especially in try-except within loops.
Example:
for i in range(1000):
try:
result = 5 / 1
except ZeroDivisionError:
pass
Output:
#nothing print
Tags:
Leave a comment
You must be logged in to post a comment.