Lecs 101
Lecs 101
C h a pter
Handling in
1 Python
In this Chapter
» Introduction
» Syntax Errors
» Exceptions 1.1 INTRODUCTION
» Built-in Exceptions Sometimes while executing a Python program, the
» Raising Exceptions program does not execute at all or the program
» Handling Exceptions executes but generates unexpected output or
behaves abnormally. These occur when there are
» Finally Clause
syntax errors, runtime errors or logical errors in
the code. In Python, exceptions are errors that
get triggered automatically. However, exceptions
can be forcefully triggered and handled through
program code. In this chapter, we will learn
about exception handling in Python programs.
2024-
25
rerun the program. When a syntax error is encountered
while working in shell mode, Python displays the name
of the error and a small description about the error as
shown in Figure 1.1.
except ValueError:
print ("Only INTEGERS should be entered")
else:
print ("The result of division operation is ", quotient)
Output:
SUMMARY
• Syntax errors or parsing errors are detected when
we have not followed the rules of the particular
programming language while writing a program.
EXERCISE
1.
“Every syntax error is an exception but every exception
cannot be a syntax error.” Justify the statement.
2. When are the following built-in exceptions raised? Give
examples to support your answers.
a) ImportError
b) IOError
c) NameError
d) ZeroDivisionError
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).
4. Use assert statement in Question No. 3 to test the
division expression in the program.
5. Define the following:
a) Exception Handling
b) Throwing an exception
c) Catching an exception
6. Explain catching exceptions using try and except block.
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")