Exception Handling
Exception Handling
Question 3
Name three run-time errors that occur during Python program execution.
Answer
TypeError, ZeroDivisionError, IndexError are the three run-time errors that occur during Python
program execution.
Question 4
What is the difference between an error and exception?
Answer
An Error is a bug in the code that causes irregular output or stops the program from executing
whereas an Exception is an irregular unexpected situation occurring during execution on which
programmer has no control.
Question 5
How can you handle an exception in Python? Write sample code to illustrate it.
Answer
In Python, we can handle exceptions using the try-except block. It includes the following steps:
1. Firstly, the moment an error occurs the state of execution of the program is saved.
2. Normal flow of the program is interrupted.
3. A special function or piece of code known as exception handler is executed.
4. Execution of the program is resumed with the previously saved data.
Here's an example of how to handle an exception:
def divide_numbers(x, y):
try:
result = x / y
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
else:
print("Division result:", result)
finally:
print("End of division operation.")
divide_numbers(10, 2)
divide_numbers(10, 0)
Output
Explain
Division result: 5.0
End of division operation.
Error: Division by zero is not allowed.
End of division operation.
This Python code defines a function divide_numbers that performs division between two
numbers x and y. It uses a try-except block to handle exceptions that may arise during division,
specifically the ZeroDivisionError. If a division by zero occurs, the program prints an error message
indicating that division by zero is not allowed. Otherwise, if the division operation succeeds without
any exceptions, it prints the result of the division. The finally block is executed in both cases,
indicating the end of the division operation.
Question 6
Name some common built-in exceptions in Python.
Answer
Some common built-in exceptions in Python are NameError, TypeError, ValueError, ZeroDivisionError,
AttributeError, KeyError, IndentationError, IOError, IndexError, EOFError, SyntaxError and
RuntimeError.
Question 7
What does the finally clause produce in a try...except block?
Answer
The 'finally' clause in a 'try-except' block is executed regardless of whether an exception occurs in the
'try' block or not. Its primary purpose is to ensure that certain actions or cleanup operations are
performed, before the program exits or moves on to the next code block.
Question 8
Write syntax of raise statement.
Answer
The syntax of raise statement is:
raise[exception name [, message/argument][, traceback]]
Question 9
Differentiate between IOError and IndexError.
Answer
IOError IndexError
Question 10
Show how to modify the following code so that an error is printed if the number conversion is not
successful:
val = input("Enter a number")
pval = int(val)
Answer
val = input("Enter a number: ")
try:
pval = int(val)
except ValueError:
print("Error: Conversion to integer failed.")
Output
Enter a number: 23
Question 11
Consider the code given below and fill in the blanks with appropriate error types:
loop = 1
while loop == 1:
try:
a = int(input('Enter the first number: ')
b = int(input('Enter the second number: ')
quotient = a/b
except ...............:
print("Error: Please enter only numbers")
except ...............:
print("\n Error: Second number should not be zero")
except ...............:
print("\n Unsupported operation: Check the date type")
else:
print("Great")
finally:
print("Program execution completed")
loop = int(input('Press 1 to try again !')
continue
Answer
loop = 1
while loop == 1:
try:
a = int(input('Enter the first number: '))
b = int(input('Enter the second number: '))
quotient = a / b
except ValueError:
print("Error: Please enter only numbers")
except ZeroDivisionError:
print("\n Error: Second number should not be zero")
except TypeError:
print("\n Unsupported operation: Check the data type")
else:
print("Great")
finally:
print("Program execution completed")
loop = int(input('Press 1 to try again: '))
continue
In the code:
1. The ValueError exception is used to catch errors that occur when the input cannot be
converted to an integer (e.g., if the user enters a non-numeric value).
2. The ZeroDivisionError exception is used to catch errors that occur when attempting to divide
by zero (i.e., when the second number is zero).
3. The TypeError exception is used to catch errors related to unsupported operations, such as
performing arithmetic operations on incompatible data types.