0% found this document useful (0 votes)
9 views8 pages

Understanding Python Exceptions and Handling

The document explains various aspects of exception handling in Python, including the definitions of syntax errors and exceptions, built-in exceptions, and the use of raise and assert statements. It also covers the try-except block for catching exceptions, the finally clause, and provides code examples for handling different types of errors. Additionally, it includes exercises that reinforce the concepts of exception handling.

Uploaded by

Karanveer Singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views8 pages

Understanding Python Exceptions and Handling

The document explains various aspects of exception handling in Python, including the definitions of syntax errors and exceptions, built-in exceptions, and the use of raise and assert statements. It also covers the try-except block for catching exceptions, the finally clause, and provides code examples for handling different types of errors. Additionally, it includes exercises that reinforce the concepts of exception handling.

Uploaded by

Karanveer Singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Exercise

Question 1

"Every syntax error is an exception but every exception cannot be a


syntax error." Justify the statement.
Answer
A syntax error is a specific type of exception that is detected when we
have not followed the rules of the particular programming language
while writing a program. On the other hand, an exception is a Python
object that represents any type of error or exceptional condition
encountered during program execution. This includes not only syntax
errors but also runtime errors and logical errors. Therefore, every
syntax error is an exception but every exception cannot be a syntax
error.

Question 2

When are the following built-in exceptions raised? Give examples to


support your answers.

1. ImportError
2. IOError
3. NameError
4. ZeroDivisionError

Answer
1. ImportError — It is raised when the requested module definition is
not found.
Example :
import module

Output
ModuleNotFoundError: No module named 'module'
2. IOError — It is raised when the file specified in a program statement
cannot be opened.
Example :
file = open("[Link]", "r")

Output
FileNotFoundError: [Errno 2] No such file or directory:
'[Link]'
3. NameError — It is raised when a local or global variable name is not
defined.
Example :
print(var+40)

Output
NameError: name 'var' is not defined.
4. ZeroDivisionError — It is raised when the denominator in a division
operation is zero.
Example :
print(50/0)

Output
ZeroDivisionError: division by zero

Question 3

What is the use of a raise statement? Write a code to accept two


numbers and display the quotient. Appropriate exception should be
raised if the user enters the second number (denominator) as zero (0).
Answer
The raise statement is used to throw an exception during the execution
of a program.
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
if denominator == 0:
raise ZeroDivisionError("Error: Denominator cannot be
zero.")
else:
quotient = numerator / denominator
print("Quotient:", quotient)

Output
Enter the numerator: 25
Enter the denominator: 5
Quotient: 5.0

Enter the numerator: 2


Enter the denominator: 0
Traceback (most recent call last):
File "c:\PythonPlayground\[Link]", line 4, in <module>
raise ZeroDivisionError("Error: Denominator cannot be
zero.")
ZeroDivisionError: Error: Denominator cannot be zero.

Question 4

Use assert statement in Question No. 3 to test the division expression


in the program.
Answer
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
assert denominator != 0, "Error: Denominator cannot be zero."
quotient = numerator / denominator
print("Quotient:", quotient)

Output
Enter the numerator: 12
Enter the denominator: 3
Quotient: 4.0

Enter the numerator: 5


Enter the denominator: 0
Traceback (most recent call last):
File "c:\PythonPlayground\[Link]", line 3, in <module>
assert denominator != 0, "Error: Denominator cannot be
zero."
AssertionError: Error: Denominator cannot be zero.

Question 5

Define the following:

1. Exception Handling
2. Throwing an exception
3. Catching an exception

Answer

1. Exception Handling — The process of writing additional code in


a program to give proper messages or instructions to the user
upon encountering an exception is known as exception handling.
2. Throwing an exception — Throwing an exception refers to the
process of creating an exception object and passing it to the
runtime system or the appropriate exception handler.
3. Catching an exception — Catching an exception refers to the
process of executing a suitable handler or block of code
specifically designed to handle that particular exception when it
occurs during program execution.

Question 6

Explain catching exceptions using try and except block.


Answer
An exception is said to be caught when a code that is designed to
handle a particular exception is executed. Exceptions, if any, are
caught in the try block and handled in the except block. While writing or
debugging a program, a user might doubt an exception to occur in a
particular part of the code. Such suspicious lines of codes are put
inside a try block. Every try block is followed by an except block. The
appropriate code to handle each of the possible exceptions (in the code
inside the try block) are written inside the except clause. While
executing the program, if an exception is encountered, further
execution of the code inside the try block is stopped and the control is
transferred to the except block. The syntax of try … except clause is as
follows:
try:
[ program statements where exceptions might occur]
except [exception-name]:
[ code for exception handling if the exception-name error
is encountered]

Question 7

Consider the code given below and fill in the blanks.


print("Learning Exceptions...")
try:
num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
quotient = (num1/num2)
print("Both the numbers entered were correct")
except ...............: # to enter only integers
print("Please enter only numbers")
except ...............: # Denominator should not be zero
print("Number 2 should not be zero")
else:
print("Great .. you are a good programmer")
...............: # to be executed at the end
print("JOB OVER... GO GET SOME REST")

Answer
print("Learning Exceptions...")
try:
num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
quotient = (num1 / num2)
print("Both numbers entered were correct")
except ValueError: # 1 : to enter only integers
print("Please enter only numbers")
except ZeroDivisionError: # 2 : Denominator should not be zero
print("Number 2 should not be zero")
else:
print("Great.. you are a good programmer")
finally: # 3 : to be executed at the end
print("JOB OVER... GO GET SOME REST")

Explanation

1. When using int(input("Enter the first number")) or int(input("Enter


the second number")),
the user is expected to input an integer. If the
user enters a non-integer value (like a string or a floating-point
number), a ValueError will be raised during the conversion to an
integer. The except ValueError: block is used to handle this
situation by displaying a message asking the user to enter only
numbers.
2. In the line quotient = (num1 / num2), if num2 is entered as zero, it
will lead to a ZeroDivisionError during the division operation
(num1 / num2). The except ZeroDivisionError: block is used to
handle this scenario by displaying a message informing the user
that the second number should not be zero.
3. The finally: block is used to define code that should be executed
regardless of whether an exception occurs or not.

Question 8

You have learnt how to use math module in Class XI. Write a code
where you use the wrong number of arguments for a method (say sqrt()
or pow()). Use the exception handling process to catch the ValueError
exception.
Answer
Note — The TypeError occurs when an incorrect number of arguments is
provided for a function, while the ValueError occurs when the number of
arguments are correct but they contain inappropriate values. Hence, in
the following code TypeError is raised due to providing an incorrect
number of arguments to the [Link]() and [Link]() function and it is
handled using except.
import math

try:
result = [Link](2, 3, 4, 5) # pow() expects 2 arguments,
# but 4 are provided
except TypeError:
print("TypeError occurred with [Link]()")
else:
print("Result:", result)

try:
result = [Link](9, 2) # sqrt() expects 1 argument,
# but 2 are provided
except TypeError:
print("TypeError occurred with [Link]()")
else:
print("Result:", result)

Output
TypeError occurred with [Link]()
TypeError occurred with [Link]()

Question 9

What is the use of finally clause ? Use finally clause in the problem
given in Question No. 7.
Answer
The statements inside the finally block are always executed, regardless
of whether an exception has occurred in the try block or not. It is a
common practice to use the finally clause while working with files to
ensure that the file object is closed.
print("Learning Exceptions...")
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
quotient = (num1 / num2)
print(quotient)
print("Both numbers entered were correct")
except ValueError:
print("Please enter only numbers")
except ZeroDivisionError:
print("Number 2 should not be zero")
else:
print("Great.. you are a good programmer")
finally:
print("JOB OVER... GO GET SOME REST")
Output
Learning Exceptions...
Enter the first number: 12
Enter the second number: 4
3.0
Both numbers entered were correct
Great.. you are a good programmer
JOB OVER... GO GET SOME REST

Learning Exceptions...
Enter the first number: var
Please enter only numbers
JOB OVER... GO GET SOME REST

Learning Exceptions...
Enter the first number: 33
Enter the second number: 0
Number 2 should not be zero
JOB OVER... GO GET SOME REST

You might also like