0% found this document useful (0 votes)
4 views5 pages

Chaper 06 Exception Handling Code Notes

The document discusses exception handling in Python, providing examples of using try-except blocks to manage errors such as ValueError, FileNotFoundError, and ZeroDivisionError. It also lists various built-in exceptions and their descriptions. Additionally, it demonstrates the use of else and finally blocks in exception handling with practical coding examples.

Uploaded by

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

Chaper 06 Exception Handling Code Notes

The document discusses exception handling in Python, providing examples of using try-except blocks to manage errors such as ValueError, FileNotFoundError, and ZeroDivisionError. It also lists various built-in exceptions and their descriptions. Additionally, it demonstrates the use of else and finally blocks in exception handling with practical coding examples.

Uploaded by

Saksham Mishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Class 12 CS date :- 07/8/2025

Chapter 06 . EXCEPTION HANDLING CODE

Q1. You have learnt how to use math module in class 11. Write a code where you use the wrong number of arguments for a method (saw sqrt ()) .Use the
exception handling process to catch the value error exception .

Ans :-

Import math
Print(“code to test wrong type of arguments”)
Try:
Num1=int(input(“ enter the first number “))
Result1=math.sqrt(num1)
Print(“Sqrt:”,result1)
.except ValueError: # to enter only integers
Print(“please enter only positive number”)
Try:
Num2=int(input(“ enter the second number “)) OUTPUT
Code to test wrong type of arguments
Result2=math.pow(num1,num 2) Enter the first number -9
Print(“Pow :”,result1) Please enter only positive numbers
Except value error: # to enter only integers Enter the second numbek
Print(“please enter only numbers”) Please enter only numbers
Finally: # to be executed at the end Tested only wrong types ; wrong no. of requires requires *args
Print ( “Tested pnly wrong types; wrong no. of require requires * args” Code to test wrong TYPE of arguments
Enter the first number 6
Sqrt:2.449489742783178
Enter the second number 4
Pow : 1296.0
Tested only wrong types ; wrong no of requires requires * args
Built-in Exceptions
The table below shows built-in exceptions that are usually raised in Python:

Exception Description

ArithmeticError Raised when an error occurs in numeric calculations

AssertionError Raised when an assert statement fails

AttributeError Raised when attribute reference or assignment fails

Exception Base class for all exceptions

EOFError Raised when the input() method hits an "end of file" condition (EOF)

FloatingPointError Raised when a floating point calculation fails

GeneratorExit Raised when a generator is closed (with the close() method)

ImportError Raised when an imported module does not exist

IndentationError Raised when indentation is not correct

IndexError Raised when an index of a sequence does not exist

KeyError Raised when a key does not exist in a dictionary

KeyboardInterrupt Raised when the user presses Ctrl+c, Ctrl+z or Delete

LookupError Raised when errors raised cant be found

MemoryError Raised when a program runs out of memory

NameError Raised when a variable does not exist

NotImplementedError Raised when an abstract method requires an inherited class to override the method
OSError Raised when a system related operation causes an error

OverflowError Raised when the result of a numeric calculation is too large

ReferenceError Raised when a weak reference object does not exist

RuntimeError Raised when an error occurs that do not belong to any specific exceptions

StopIteration Raised when the next() method of an iterator has no further values

SyntaxError Raised when a syntax error occurs

TabError Raised when indentation consists of tabs or spaces

SystemError Raised when a system error occurs

SystemExit Raised when the sys.exit() function is called

TypeError Raised when two different types are combined

UnboundLocalError Raised when a local variable is referenced before assignment

UnicodeError Raised when a unicode problem occurs

UnicodeEncodeError Raised when a unicode encoding problem occurs

UnicodeDecodeError Raised when a unicode decoding problem occurs

UnicodeTranslateError Raised when a unicode translation problem occurs

ValueError Raised when there is a wrong value in a specified data type

ZeroDivisionError Raised when the second operator in a division is zero


Q2. Imagine you’re driving a car. If you encounter a roadblock, you find an alternative route instead of giving up. Similarly, in programming, try-
except blocks help your program find an alternative path when errors occur. Define the output .
try:
file = open("nonexistent_file.txt", "r")
content = file.read()
print(content)
file.close()
except FileNotFoundError:
print("The file does not exist!")
# Example of handling PermissionError
try:
file = open("/etc/sensitive_file.txt", "w")
file.write("Top secret information!")
file.close()
Output :- ?
except PermissionError:
print("You don't have permission to write to this file!")
# Example of handling IOError
try:
file = open("corrupted_file.txt", "r")
content = file.read()
print(content)
file.close()
except IOError:
print("An error occurred while reading the file!")
Q3. How to uses two except blocks to process two different exception types

Ans .try:
a=5
b=0
print (a/b) Output
except TypeError:
print('Unsupported operation') Division by zero not allowed Out of try
except ZeroDivisionError: except blocks
print ('Division by zero not allowed')
except:
print('Some error occurred.')
print ('Out of try except blocks')

Q4. The example below accepts two numbers from the user and performs their division. It demonstrates the uses of else
and finally blocks.
Anstry:
x,y = 10, 2
z=x/y
except ZeroDivisionError:
print("except ZeroDivisionError block")
print("Division by 0 not accepted") Output
except:
print('Some error occurred.') Division = 5.0 Executing finally block
else: Out of try, except, else and finally
print("Division = ", z) blocks.
finally:
print("Executing finally block")
x=0
y=0
print ("Out of try, except, else and finally blocks." )

You might also like