Parts
- Most Asked Python Interview Questions — Part-1 (Classes)
- Most Asked Python Interview Questions — Part-2 (Exception Handling)
Welcome back to the second part of our Most Asked Python Interview Questions series. In this part, we will dive into the critical topic of Exception Handling in Python. Exception handling is a fundamental aspect of writing robust and error-resistant code. During interviews, employers often probe candidates’ understanding of how to handle errors gracefully and maintain the stability of their programs.
I am assuming that you guys already know how a simple try-except block works but still, let’s take a small example
try:
# Code that may raise an exception
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Cannot divide by zero.")
The code inside the “try” block is monitored for exceptions. If an exception occurs, the code inside the corresponding “except” block is executed, allowing the program to handle the error and continue its execution.
Now, let’s understand some of the main concepts of exception handling before jumping into exercises.
try-except-else block
If no exceptions occur in the try
block, then else
block code executed. It is optional but often used when you want to perform some actions when there are no exceptions.
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("Division successful:", result)
# Output:
# Division successful: 5.0
As you can see in the above example, try executed successfully, and after that else
block executed too.
Multiple Exceptions
Python allows you to handle multiple exceptions by providing multiple “except” blocks. When an exception occurs, Python checks each “except” block sequentially until it finds a match, and the corresponding block is executed.
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid input. Please enter a valid number.")
else:
print("Division successful:", result)
# Enter a number: 2
# Division successful: 5.0
# Enter a number: 0
# Cannot divide by zero.
As you can see, if we pass 2
to num
it executed successfully with else
block but if we pass 0
then it raised Cannot divide by zero
error.
finally Block
Very important concepts and must asked question in the interviews.
So The finally
block is used to define code that should always be executed, regardless of whether an exception occurs or not
Use Case: It is generally used for cleanup activities like closing files or releasing resources.
try:
num = 2
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid input. Please enter a valid number.")
else:
print("Division successful:", result)
finally:
print("Cleanup: This will always be executed.")
# Division successful: 5.0
# Cleanup: This will always be executed.
Expected Output:
Division successful: 5.0
Cleanup: This will always be executed.
In the above example, the try
block executed successfully, and after that, the else
block also executed. Finally, the finally
block was executed, regardless of whether an exception occurred or not.
Now let’s start with some exercises.
Exercise-1
try:
print("Inside the try block")
finally:
print("Inside the finally block")
Expected Output:
Inside the try block
Inside the finally block
- The
try
block will be executed first and will print "Inside the try block". - After executing the
try
block, thefinally
block will always be executed, regardless of whether an exception occurred or not. Thefinally
block will print "Inside the finally block".
So, both print statements in the try
and finally
blocks will be executed, resulting in the output as shown above.
Exercise-2
try:
return 10
finally:
return 20
Expected Output:
20
If a return
statement is encountered inside the finally
block, it can override any previous return value set in the try
or except
block.
In this case, the return 20
statement in the finally
block takes precedence over the return 10
in the try
block.
Exercise-3
def divide_numbers(a, b):
try:
result = a / b
else:
print("Division successful!")
finally:
print("This block will always be executed.")
divide_numbers(5, 0)
Expected Output:
SyntaxError: invalid syntax
It raises a syntax error because the else
block is used without a preceding except
block which is not allowed in Python.
Exercise-4
try:
num = 5 / 0
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except Exception as e:
print("There is an Exception")
else:
print("I am else")
Expected Output:
Error: Cannot divide by zero.
In this code, a try
block is used to attempt a division operation 5 / 0
, which will raise a ZeroDivisionError
. The except
block with ZeroDivisionError
catches this specific error and prints the message "Error: Cannot divide by zero."
If there were any other exceptions occurring during the execution of the try
block, the except
block with Exception
would catch those, and it would print "There is an Exception."
Exercise-5
try:
print([1, 2, 3, 4][4])
except Exception:
print("I am Exception block")
except IndexError:
print("I am IndexError block")
else:
print("I am else block")
finally:
print("I am finally block")
Expected Output:
I am Exception block
I am finally block
try
block will raise IndexError
exception but it will enter the except Exception
block first. Therefore, the except Exception
block will catch the IndexError
before it reaches the more specific except IndexError
block.
Exercise-6
try:
print([1, 2, 3, 4][4])
except IndexError:
print(5 / 0)
except ZeroDivisionError:
print("I am ZeroDivisionError block")
except Exception:
print("I am Exception block")
else:
print("I am else block")
finally:
print("I am finally block")
Expected Output:
ZeroDivisionError: division by zero
Above code will raise Unhandled exception ZeroDivisionError
.
In the given code, an attempt is made to access an element at index 4 in the list [1, 2, 3, 4]
, causing an IndexError, As a result, the program enters the except IndexError
block, where a division by zero operation is performed (print(5 / 0)
), leading to a ZeroDivisionError. However, there is no exception handling inside the except IndexError
to handle this exception, causing the program to terminate abruptly and display the error message ZeroDivisionError: division by zero.
The finally
block is not executed in this scenario because the program terminates before reaching that point.
Final Words
I hope this second part in the series helps you out to refresh some of main concepts of Exception Handling in Python.
And exercise will help you out too to prepare for the interview.
See ya till next time. HAPPY CODING!
Don’t forget to connect on LinkedIn