0% found this document useful (0 votes)
14 views14 pages

Exception

The document provides an overview of exception handling in Python, including definitions, mechanisms for handling exceptions, and the importance of exceptions in programming. It covers various topics such as try-except blocks, raising exceptions, user-defined exceptions, and the differences between errors and exceptions. Additionally, the document includes examples and explanations of concepts like the else and finally blocks in exception handling.
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)
14 views14 pages

Exception

The document provides an overview of exception handling in Python, including definitions, mechanisms for handling exceptions, and the importance of exceptions in programming. It covers various topics such as try-except blocks, raising exceptions, user-defined exceptions, and the differences between errors and exceptions. Additionally, the document includes examples and explanations of concepts like the else and finally blocks in exception handling.
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

UNIT-3

Important Questions on Exceptions

(1) What is exception? (or) Define exception.


Ans: Exceptions are raised when the program is syntactically correct, but the code
resulted in an error. This error does not stop the execution of the program, however, it
changes the normal flow of the program.
(or)
An exception is an error that happens during execution of a program. When that Error
occurs.
(or)
An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program.

When a python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.
(2) What are the different mechanisms for handling the exception?
Ans:
1. try – except
2. try – multiple except
3. try – except-else
4. raise exception
5. try – except-finally
(3) List and describe the standard built in Exceptions. (or) Explain Python Built-in Exceptions?
Ans:
(4) What happens if the exception is not handled in python program?
Ans: When a python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.
(5) Why there is a need for exceptions now?
Ans: Following are the reasons why there is a need for exception now
(i) Modern systems are becoming more complex.
(ii) The number of users are also getting increased day by day. And the user demands for
smoothly execution of the application.
(iii) Even in error situation, an application should terminate successfully so that the rest of
the execution environment should not get disturbed and the error should be gracefully
handled.
(iv) Python’s exception handling promotes mature (fully developed) and correct
programming.

(6) Justify – why exception at all?


Ans:
 An exception is an error that happens during execution of a program. When that
error occurs, python generate an exception that can be handled, which avoids the
program to crash.
 Exceptions are convenient in many ways for handling errors and special conditions in
a program.
 When there are chances that the code can produce error then we can use exception
handling
 Raising an exception breaks current code execution and returns the exception back
until it is handled.
(7) How to use else clause in exception handling?
Ans:
 Else block will execute only when no exception occurs.
 The code enters the else block only if the try clause does not raise an exception.

Example:
[Link]
def divide(x,y):
try:
result = x // y
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
else:
print("Yeah ! Your answer is :", result)
divide(3, 2)

divide(3, 0)
Output:
Yeah ! Your answer is : 1

Sorry ! You are dividing by zero

(8) What is raising of exception? Explain it with suitable example (or) How to raise the
exceptions manually? Demonstrate with an example.
Ans:
 Raising an exception is a technique for interrupting the normal flow of execution
in a program.
 The python interpreter raises an exception each time it detects an error in an
expression or statement.
 Users can also manually raise exceptions using the raise keyword.
 The raise statement allows the programmer to force a specified exception to
occur.
 Syntax:
Raise[Exception[,args[,traceback]]]
Here,
Exception is a type of exception (For example NameError)
args is value for exception argument.
traceback is object of traceback

Example:
>>> raise NameError('HiThere') # Raising Exception
Output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: HiThere
(9) How does try-except statement work? Demonstrate with an example python code.
(or)
How to handle an exception using try except block? Explain with help of a program.
(or)
Discuss about try except block with example.
(or)
Explain try except block in detail.
Ans:
 Try and except statements are used to catch and handle exceptions in Python.
 statements that can raise exceptions are kept inside the try clause and the
statements that handle the exception are written inside except clause.
 The try and except statements are used to handle runtime errors
 Syntax:
try :
statements
except :
statements

 The try-except statement works as follows:-


First, the try clause (the statement(s) between the try and except keywords) is
executed.
If no exception occurs, the except clause is skipped and execution of the try
statement is finished.
 If an exception occurs during execution of the try clause, the rest of the clause
is skipped. Then if its type matches the exception named after the except
keyword, the except clause is executed, and then execution continues after the try
statement.
Example:
[Link]
X=int(input(“Enter the value of X”))
Y=int(input(“Enter the value of Y”))
try:
result = X / ( X – Y )
print(“result=”.result)
except ZeroDivisionError:
print(“Division by Zero”)
Output:

(10) State the syntax for try…except block.


Ans: The try and except statements are used to handle runtime errors
try :
statements
except :
statements
(11) What is the difference between else block and finally block in exception handling?
Explain with an example program.

Ans: The difference between else block and finally block in exception handling is

else block finally block


else block (or) clause is executed only if the A finally block (or) clause is always
statements in the try block don't raise an executed before leaving the try statement,
exception. whether an exception has occurred or not.
Example: Example:
Diff else and [Link] Diff else and [Link]
X=int(input('Enter the value of X')) X=int(input('Enter the value of X: '))
Y=int(input('Enter the value of Y')) Y=int(input('Enter the value of Y: '))
try: try:
result = X/(X-Y) result = X/(X-Y)
except ZeroDivisionError: except ZeroDivisionError:
print('Division by Zero') print('Division by Zero')
else: else:
print('result=',result) print('result=',result)
finally:
print ('executing finally clause')
Output: Output:
Enter the value of X: 10 Enter the value of X: 10
Enter the value of Y: 5 Enter the value of Y: 10
result= 2.0 Division by Zero
executing finally clause

(12) What happens if except clause is written without any Exception type? Explain with
an example.

(13) How to create, raise and handle user defined exceptions in Python. (or) How to create a
user defined exception? Explain. (or) Elaborate user defined exceptions in Python? (or) Write a
program to create customized (your own) exception.
Ans:

 sometimes the built-in exceptions like IndexError, IOError, ImportError,


ZeroDivisionError, TypeError, etc. are not enough to handle the exceptions. So, we have
to create some custom exceptions to handle the errors in a better way and to create
more meaningful exceptions.
 custom exceptions are also termed as user-defined exceptions.
User Defined Exception in Python: Follow the steps below.

Step 1: Create User Defined Exception

(i) To create a custom (or) user defined Exception we must create a new class. This exception
class has to be derived, directly or indirectly, from the built-in Exception class.

(ii) Usually, the defined exception name ends with the word Error which follows the
standard naming convention, however, it is not compulsory to do so.

Example: creating exception

[Link]

class PowerfulError(Exception):
print("Custom Error")
Here, in the above program, we have defined a user-defined exception with the name
PowerfulError inherited from the class Exception. Inside the PowerfulError class, we have written
the print statement to check if it is being called.

Output

Custom Error

Step 2: raise User Defined Exception


using raise keyword to raise the user-defined exception.

Example: raising exception

[Link]
class PowerfulError(Exception):

print("Custom Error")

raise PowerfulError("Error Present")

Output

Custom Error
Traceback (most recent call last):
File "F:/PYTHON NOTES/[Link]", line 3, in <module>
raise PowerfulError("Error Present")
PowerfulError: Error Present
Step 3: handling User Defined Exception
For handling user defined exception use try-except block.

Example: handling exception

[Link]

class PowerfulError(Exception):
print("Custom Error")
try:
raise PowerfulError("Error Present")
except PowerfulError as err:
print('[Link]:',err)

Output

Custom Error
[Link]: Error Present

(12) Write a function called oops that explicitly raises a IndexError exception when called. Then
write another function that calls oops inside a try/except statement to catch the error. What
happens if you change oops to raise KeyError instead of IndexError? Where do the names KeyError
and IndexError come from?

(13)

(14) Discuss with an example exception with arguments in python.

Ans: The arguments in python will give additional information about the exception
raised by Python.
 The contents of the argument vary by exception.
 If we write the code to handle a single exception, we can have argument follow the name
of the exception in the except statement. If we have multiple exceptions, we can have a
arguments follow the tuple of the exception.

Syntax:
try:
statements
except ExceptionType, Argument:
statements

Example:

try:
b = float (100 + 50 / 0)
except Exception as Argument:
print ('This is the Argument\n', Argument)

output:
This is the Argument
division by zero

(15)

(16)

(17) Define error and exception. Distinguish between these two features.

(or)

Write about Errors and Exception Handling in Python programming?

Ans: Error: Error is a mistake in python also referred as bugs .they are almost always the
fault of the programmer.
 The process of finding and eliminating errors is called debugging.
Exception: An exception is an event, which occurs during the execution of a program
that disrupts the normal flow of the program.

Error Exception
1. Error is a mistake in python also 1. An exception is an event, which
referred as bugs. They are almost always occurs during the execution of a
the fault of the programmer. program that disrupts the normal flow of
the program.
2. Types of errors 2. Types of Exceptions
o Syntax error or compile time error IO Error-If the file cannot be opened.
o Run time error · Import Error -If python cannot find the
o Logical error module
· Value Error -Raised when a built-in
operation or function receives an
argument that
has the right type but an inappropriate
value
· Keyboard Interrupt -Raised when the
user hits the interrupt
· EOF Error -Raised when one of the
built-in functions (input() or raw_input())
hits an
end-of-file condition (EOF) without
reading any data
3. The process of finding and eliminating 3. Exception Handling Mechanisms are
errors is called debugging i. try –except
ii. try –multiple except
iii. try –except-else
iv. raise exception
v. try –except-finally

(18) Explain about handling an exception.

(19)

(20)

(21)

(22)

(23)
(24) Explain in detail about try, except, finally, else with an example.

Ans:
The else part will be executed only if the try block does not raise the exception.
 Python will try to process all the statements inside try block. If value error occur,the flow
of control will immediately pass to the except block and remaining statements in try block
will be skipped.
 A finally clause is always executed before leaving the try statement, whether an
exception has occurred or not.
The finally clause is also executed “on the way out” when any other clause of the
try statement is left via a break, continue or return statement.
Syntax
try:
statements
except:
statements
else:
statements
finally:
statements
Example:
[Link]
X=int(input("Enter the value of X: "))
Y=int(input("Enter the value of Y: "))
try:
result = X/(X-Y)
except ZeroDivisionError:
print("Division by Zero")
else:
print("result=",result)
finally:
print ("executing finally clause")

Output:1
Enter the value of X: 10
Enter the value of Y: 5
result= 2.0
executing finally clause

Output:2
Enter the value of X: 10
Enter the value of Y: 10
Division by Zero
executing finally clause

(25) Write a program to handle ZeroDivisionError, ValueError, TypeError, where


ZeroDivisionError is handled by one except block only ValueError and TypeError is
handled by other except block.

(26) Explain in detail about nested try and except blocks with an example
Ans: In python nested try except finally blocks are allowed. We can take try-except-finally
blocks inside try block. We can take try-except-finally blocks inside except block. We can
take try-except-finally blocks inside finally block

Example: nested [Link]


a = {"a": 5,"b": 25,"c": 125,"e": 625,"f": 3125}
try:
try:
print("d:", a["d"])
except:
print("a:", a["a"])
finally:
print("First nested finally")
except KeyError:
try:
print("b:", a["b"])
except:
print("No value exists for keys 'b' and 'd'")
finally:
print("Second nested finally")
finally:
try:
print("c:", a["c"])
except:
print("No value exists for key 'c'")
finally:
print("Third nested finally")

Output:
a: 5
First nested finally
c: 125
Third nested finally

(27) Write a program try with multiple except blocks with an example. (or)
Explain about except clause with multiple exceptions.

Ans: Exception type must be different for except statements


Syntax:
try:
statements
except errors1:
statements
except errors2:
statements
except errors3:
statements
Example: multiple except [Link]
X=int(input("Enter the value of X: "))
Y=int(input("Enter the value of y: "))
try:
sum = X + Y
divide = X/Y
print ("Sum of X and Y = ",sum)
print ("Division of X and Y = ",divide)
except NameError:
print("The input must be number")
except ZeroDivisionError:
print("Division by Zero")

Output:1
Enter the value of X: 10
Enter the value of y: 5
Sum of X and Y = 15
Division of X and Y = 2.0
Output:2
Enter the value of X: 10
Enter the value of y: 0
Division by Zero

Output:3

Enter the value of X = 10


Enter the value of Y = a
The input must be number

(28) Write a program to demonstrate else block in exception handling.

Ans: else block (or) clause is executed only if the statements in the try block don't raise an exception.

Example: [Link]

X=int(input('Enter the value of X'))


Y=int(input('Enter the value of Y'))
try:
result = X/(X-Y)
except ZeroDivisionError:
print('Division by Zero')
else:
print('result=',result)

Output:1

Enter the value of X: 10

Enter the value of Y: 5

result= 2.0

Output: 2
Enter the value of X = 10
Enter the value of Y = 10
Division by Zero
(29)
What type of exception is raised for the following code?
a=[ ]
print(a[1])
Ans:IndexError: list index out of range

(30) Explain the purpose and use of the function exc_info( ). (or)
What is the use of sys. exc_info( ) function?
Ans: The exc_info( ) function is used for obtaining the information about an exception. For
using this function we need to import the sys module at the beginning of the python
program.

 This function returns a tuple of three values that give information about the exception
that is currently being handled.

 The values returned are from this function are (type, value, traceback)
Their meaning is
type gets the exception type of the exception being handled (a class object)
value gets the exception parameter (its associated value or the second argument to
raise, which is always a class instance if the exception type is a class object)
traceback gets a traceback object

Example:
[Link]
import sys
try:
1/0
except ZeroDivisionError:
print(sys.exc_info ( ))

output:
(<class 'ZeroDivisionError'>, ZeroDivisionError('division by zero'), <traceback object at
0x0000016E5AD44140>)

(31) Explain the Concept of context management in Python?


Ans: Context management is a mechanism in which the resources are allocated and
released as per the requirements.
 The with statement is a control-flow structure that allows us to encapsulate try…
except…finally blocks for convenient reuse.

 The with statement supports a runtime context which is implemented through a pair of
methods executed.
(i) before the statement body is entered (__enter__( )) and
(ii) after the statement body is exited (__exit__( ))
 The basic structure looks as follows:
with context-expression [as var]:
with_statement_body

Example:
 The most widely used example of context management is the with statement. Suppose
we have two related operations which need to be executed as a pair, with a block of code in
between. Context management allows this in following manner.

With open(‘some_file’,‘w’) as opened_file:


Opened_file.write(‘Hello!’)
 The above code opens the file, writes some data to it and then closes it. If an error occurs
while writing the data to the file, it tries to close it. The above code is equivalent to:

file = open(‘some_file’,‘w’)
try:
[Link](‘Hello!’)
finally:
[Link]( )

 If the file object raises an exception then the same with statement can be modified as
with open(‘some_file’,‘w’) as opened_file:
opened_file.undefined_function(‘Hello!’)

(32) Explain the concept of assertions in Python


Ans:
 Assertions are the statements that evaluate to true.
 If the expression is false , python raises an AssertionError exception.
Syntax:
assert Expression[, Arguments]
 If the assertion fails, python uses ArgumentExpression as the argument for the
AssertionError.
 AssertionError exceptions can be caught and handled like any other exception using
the try-except statement.

For Example:
>>>assert 1 ==1
>>>assert 1*1 == 1/1
 AssertionError exception can be caught and handled like any other exception using the
try-except statement, but if not handled, they will terminate the program and produce a
traceback similar to the following:
>>>assert 1 == 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError

 The above situation can be handled by try-except statement as follows-


try:
assert 1==0, ‘This is an unequality’
except AssertionError, args:
print ‘%s: %s’ % (args._class_._name_,args)
output:
AssertionError: This is an unequality

You might also like