II - I - CSE - Python Programming - Unit-2 - Exceptions - Mate - 240426 - 180429
II - I - CSE - Python Programming - Unit-2 - Exceptions - Mate - 240426 - 180429
Learning)
Python Programming – II Year B.Tech II Semester
Course Instructor: Prof.B.Sreenivasu, 9502251564, 9550411738
------------------------------------------------------------------------------------------------------------------------------
==========================================================================================================
Exceptions: Exceptions in Python, Detecting and Handling Exceptions, Context Management, *Exceptions
as Strings, Raising Exceptions, Assertions, Standard Exceptions, *Creating Exceptions.
==========================================================================================================
Exceptions:
● What is Exception?
● Why exception handling?
● Syntax error v/s Runtime error
● Detecting and Handling Exceptions
● Handling exception – with help of using try block and except blocks or try with multi except blocks
● Handling multiple exceptions with single except block
● Handling exception with help of using ==>
❖ try-except
❖ Try-except-finally
❖ Try with finally
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 1 of 22
All compile time errors are called syntax errors. If there is a syntax error within program. program is not
executed.
Note:
• When the proper syntax of the language is not followed then a syntax error is thrown.
• Syntax errors must be rectified by programmer in order to execute program.
Logic error:
▪ Logical errors occur due to our mistakes in programming logic.
▪ A program with logical errors compiles successfully and executes but does not generate the desired
results.
▪ Logical errors are no caught by compiler. It has be identified and corrected by the programmer /
developer.
Example:
==========================================================================================================
OUTPUT:
Enter first floating point number: 4.5
Enter second floating point number: 2.9
average of two numbers4.5 and 2.9 is 5.95
==========================================================================================================
Note: The results mentioned above is incorrect. Because according to the operator
precedence, division is evaluated first before addition.
Exceptions: An exception is a type of error that occurs when a syntactically correct python code raises an
error during execution time / run time. If run time errors are not handled program gets terminated.
Runtime Errors:
Even if a python code (python program) is syntactically correct, it may still raise error when
executed.
Runtime errors occurs because of wrong input / invalid input given by end user. When runtime error occurs,
program execution is terminated.
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 2 of 22
Key note: An error which is occurred during execution of program is called runtime error.
An exception is a run time error which can be handled by the programmers.
Exception handling:
▪ Exception handling or Error handling means handling runtime errors.
▪ Exception is a runtime error.
▪ When a python program raises an exception, it must handle the exception otherwise program will
be immediately terminated.
▪ We can handle exceptions (runtime errors) by making python program more robust.
Python provides the following keywords to handle exceptions/errors:
1. try
2. except
3. finally
4. raise
We can handle exceptions in python program by using try block and except block.
Advantage of error handling or exception handling:
1.Avoiding abnormal termination program
2.Converting predefined error messages or codes into user defined error message
Key note:
❖ Every error is one class or type in python. Creating object of error class/type and giving to PVM is
called raising an error or generating error.
❖ An error generated in function during execution / run time if wrong input is given by end user.
Exceptions are of two types:
1. Predefined exceptions / error types (Built-in exceptions)
2. User defined exceptions/error types
Imp. Note:
Exception is a root class or base class for all exception types.
Syntax:
try:
try_suite / statement(s) #watch for exception here
except block:
except block is an error handling block. If there is an error inside try block, that error is handled by except
block.
try block followed by one or more except blocks.
Syntax:
try:
statement-1
statement-2
except <error-type> as <variable-name>:
statement-3 #exception handling code
except <error-type> as <variable-name>:
statement-4
Note: except block contains logic to convert predefined error message into user defined message.
OUTPUT:
Traceback (most recent call last):
File "C:\Users\Sreenivasu\Desktop\cse_exception.py", line 3, in <module>
print(x)
NameError: name 'x' is not defined
OUTPUT:
Dear user look into program
Example:
Predefined exception type with description:
exception ZeroDivisionError
Raised when the second argument / parameter of a division or modulo operation is zero.
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 5 of 22
# Write a python program to handle the divide zero exception
while True:
num1=int(input("Enter First Number "))
num2=int(input("Enter Second Number "))
try:
div=num1/num2
print(" Result of division is", div)
print(f'Result of division of {num1} and {num2} is {div:.2f}') #formatting output using f'string
break
except ZeroDivisionError:
print(" You Cannot Divide a Number with zero")
print("Dear Sreenivasu Enter valid inputs...")
OUTPUT:
OUTPUT:
raise keyword:
A function generates error using raise keyword.
Generating error is creating error object and giving to PVM (python virtual machine).
Syntax:
raise <error-type-name>()
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 6 of 22
n1=int(input("Enter first num "))
n2=int(input("Enter second num "))
res=division(n1,n2) #calling function
print("result of division", res)
OUTPUT:
OUTPUT:
while True:
try:
num1=int(input("Enter First Number "))
num2=int(input("Enter Second Number "))
num3=multiply(num1,num2)
print(num1,num2,num3)
break
except ValueError:
print("Numbers cannot multiply with zero")
print("Pls enter numbers again")
OUTPUT:
Enter First Number 4
Enter Second Number 6
4 6 24
OUTPUT:
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 7 of 22
Enter First Number 1
Enter Second Number 0
Numbers cannot multiply with zero
Pls enter numbers again
Enter First Number 0
Enter Second Number 4
Numbers cannot multiply with zero
Pls enter numbers again
Enter First Number 6
Enter Second Number 9
6 9 54
OUTPUT:
enter any number56
3136
enter any number
you should have entered a number.....program terminating
raise keyword:
Note: you can deliberately raise an exception using raise keyword
syntax for the raise statement is
raise <exception>
OUTPUT:
Enter any number56
56
Exception occurred....program terminating
except ZeroDivisionError:
print("you can not divide a number by zero....program terminating")
a=int(input("Enter a : "))
b=int(input("Enter b : "))
res=divide(a,b) #calling function
print(res)
OUTPUT:
Enter a : 45
Enter b : 9
5.0
OUTPUT:
Enter a : 45
Enter b : 0
you can not divide a number by zero....program terminating
None
try:
a=int(input("Enter a : "))
b=int(input("Enter b : "))
res=divide(a,b)
print(res)
except ZeroDivisionError:
print("you can not divide a number by zero....program terminating")
OUTPUT:
Enter a : 84
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 9 of 22
Enter b : 16
5.25
OUTPUT:
Enter a : 68
Enter b : 0
you can not divide a number by zero....program terminating
finally block:
➢ finally is a keyword.
➢ finally block is not exception handler.
➢ finally block is used to de-allocate the resources allocated within try block.
➢ finally block contains statements which are executed after execution of try block and except
block.
➢ The 'finally' block contains code that will always be executed, regardless of whether an exception
occurs or not within the “try” block.
➢ The finally block is always executed, so it is generally used for doing the concluding tasks like
closing file resources or closing database connection.
#Example python program to demonstrate use of try, except and finally blocks
try:
print("inside try block")
a=int(input("Enter value of a "))
b=int(input("Enter value of b "))
c=a/b
print(f'division of {a} and {b} is {c:.2f}')
except:
print("inside except block")
print("Dear User,Exception occurred..>ValueError..>Enter valid input")
finally:
print("inside finally block")
print("it's ok")
OUTPUT:
OUTPUT:
Output:
Enter First Number 5
Enter Second Number 0
cannot divide number with zero
Output:
Enter First Number
Traceback (most recent call last):
File "C:/Users/Sreenivasu/Desktop/Exception programs/11_11_2023_try.py", line 2, in <module>
n1=int(input("Enter First Number "))
KeyboardInterrupt
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 11 of 22
Note: In above python program we have except blocks to handle ValueError and ZeroDivisionError but
there is no except block to handle KeyboardInterrupt error which is raised when the user inputs interrupt
keys (Ctrl + C or Delete)
Example:
try:
n1=int(input("Enter First Number "))
n2=int(input("Enter Second Number "))
div_res=n1/n2
print(f'Result is {div_res}')
except:
print("cannot divide number with zero or input only numbers ")
Output:
Enter First Number 45
Enter Second Number 9
Result is 5.0
Note: KeyboardInterrupt error which is raised when the user inputs interrupt keys (Ctrl + C)
try:
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 12 of 22
value =cse_list[4]
print(value)
except IndexError as e:
print(" An index error occurred : ", e)
OUTPUT:
OUTPUT:
exception occurred...>specified file is not found
else block:
➢ the try and except block can optionally have an else block
➢ the statements in the else block is executed only if the try block does not raise an exception.
For example, the python code given below illustrates both the cases
OUTPUT:
543 tej 89 45
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 13 of 22
except IOError:
print("Error occurred during input....program terminating")
else:
print("Program terminating successfully")
OUTPUT:
Error occurred during input....program terminating
=================================================================================================================
Note: built-in exceptions in Python:
(Python 3.11.4 documentation
Welcome! This is the official documentation for Python 3.11.4.)
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 14 of 22
Built-in Exceptions in python as per official documentation for Python 3.11.4:
In Python, all exceptions must be instances of a class that derives from BaseException. In a try statement
with an except clause that mentions a particular class, that clause also handles any exception classes
derived from that class
Exceptions hierarchy:
The class hierarchy for built-in exceptions is:
BaseException
├── BaseExceptionGroup
├── GeneratorExit
├── KeyboardInterrupt
├── SystemExit
└── Exception
├── ArithmeticError
│ ├── FloatingPointError
│ ├── OverflowError
│ └── ZeroDivisionError
├── AssertionError
├── AttributeError
├── BufferError
├── EOFError
├── ExceptionGroup [BaseExceptionGroup]
├── ImportError
│ └── ModuleNotFoundError
├── LookupError
│ ├── IndexError
│ └── KeyError
├── MemoryError
├── NameError
│ └── UnboundLocalError
├── OSError
│ ├── BlockingIOError
│ ├── ChildProcessError
│ ├── ConnectionError
│ │ ├── BrokenPipeError
│ │ ├── ConnectionAbortedError
│ │ ├── ConnectionRefusedError
│ │ └── ConnectionResetError
│ ├── FileExistsError
│ ├── FileNotFoundError
│ ├── InterruptedError
│ ├── IsADirectoryError
│ ├── NotADirectoryError
│ ├── PermissionError
│ ├── ProcessLookupError
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 15 of 22
│ └── TimeoutError
├── ReferenceError
├── RuntimeError
│ ├── NotImplementedError
│ └── RecursionError
├── StopAsyncIteration
├── StopIteration
├── SyntaxError
│ └── IndentationError
│ └── TabError
├── SystemError
├── TypeError
├── ValueError
│ └── UnicodeError
│ ├── UnicodeDecodeError
│ ├── UnicodeEncodeError
│ └── UnicodeTranslateError
└── Warning
├── BytesWarning
├── DeprecationWarning
├── EncodingWarning
├── FutureWarning
├── ImportWarning
├── PendingDeprecationWarning
├── ResourceWarning
├── RuntimeWarning
├── SyntaxWarning
├── UnicodeWarning
└── UserWarning
=================================================================================================================
sys.exc_info()
This function returns the old-style representation of the handled exception. If an exception e is currently
handled (so exception() would return e), exc_info() returns the tuple (type(e), e, e.__traceback__). That
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 16 of 22
is, a tuple containing the type of the exception (a subclass of BaseException), the exception itself, and
a traceback object which typically encapsulates the call stack at the point where the exception last
occurred.
import sys
try:
n1=int(input("Enter First Number "))
n2=int(input("Enter Second Number "))
n3=n1/n2
print(f'Result is {n3}')
except:
t=sys.exc_info()
print(t[1])
OUTPUT:
Creating Exceptions:
▪ Each time an error is detected in a program, the python interpreter raises (throws) an exception.
▪ Programmers can also raise exceptions in a program using the raise and assert statements.
User defined exceptions:
▪ Every exception is a derived class from exception class(exception is base class).
▪ All the exception either built-in or user defined all are derived class from exception class.
class CustomError(Exception):
...
pass
try:
...
except CustomError:
...
Note: CustomError is a user defined error / exception which inherits from the Exception class which is a
base class for all built-in and user defined exceptions.
Syntax:
assert <condition>, <error message>
Key note: if the condition is False, then the exception by the name AssertionError is raised along with the
message written in the assert statement. If the message is not given in the assert statement and the condition
is False, then also AssertionError is raised without message.
OUTPUT:
Traceback (most recent call last):
File "C:/Users/Sreenivasu/Desktop/assert.py", line 5, in <module>
assert str=="Python", "str should be PYTHON"
AssertionError: str should be PYTHON
OUTPUT:
#python program using the assert statement with a message and catching AssertionError
try:
x=int(input("Enter a number between 5 and 10: "))
assert x>=5 and x<=10, "Your input is not correct"
print("the number entered: ",x)
except AssertionError as obj:
print(obj)
OUTPUT:
Enter a number between 5 and 10: 34
Your input is not correct
Note: When the condition in assert statement is False, the message is passed to AssertionError object ‘obj’
that can be displayed in the except block as shown in above program.
#python program to create user defined exception called “InvalidData” which is derived class from
#Exception class => exception class is base class for all built-in and user defined exceptions
class InvalidData(Exception):
pass
marks=int(input("Enter marks for students: "))
try:
if marks<0 or marks>100:
raise InvalidData
except InvalidData:
print("Student marks should be in between 0 and 100")
OUTPUT:
Enter marks for students: 105
Student marks should be in between 0 and 100
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 19 of 22
Important Note: In above program we have created exception called “InvalidData” which is derived class
from Exception class => exception class is base class for all built-in and user defined exceptions
class InvalidAgeException(Exception):
"Raised when input value is less than 18"
pass
age_vote=18
try:
age=int(input("Enter age: "))
if age<age_vote:
raise InvalidAgeException
else:
print("eligible to vote")
except InvalidAgeException:
print("Exception occurred: Invalid age")
OUTPUT:
Enter age: 45
eligible to vote
Enter age: 13
Exception occurred: Invalid age
Enter age: 12
Exception occurred: Invalid age
class LoginError(Exception):
def __init__(self):
super().__init__()
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 20 of 22
def login(user,pwd):
if user in users and users[user]==pwd:
return True
else:
raise LoginError()
try:
uname=input("UserName ")
password=input("Password ")
if login(uname,password):
print(f'{uname} welcome')
except LoginError:
print("invalid username or password")
OUTPUT:
UserName cse_ab
Password cr123
cse_ab welcome
*****
Sample Review Questions:
1. Differentiate between error and exception.
2. What will happen if an exception occurs but is not handled by the program?
3. Explain the syntax of try-except block
4. Explain how to handle an exceptions in python.
5. What is the difference between try-except and try-finally?
6. Elaborate on raise statement used to raise exceptions.
7. Write a python program to illustrate “FileNotFoundError” exception.
8. Write a python program for creating custom exception ‘loginError’
Reference Books:
==========================================================================================================
Dear Students,
During your preparation for the examinations / interview questions, you can refer / use below mentioned
websites for material / for coding exercises / coding practice.
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 21 of 22
for Python Developer Interview Questions: for Interview questions
1. https://www.interviewbit.com/python-interview-questions
2. https://quescol.com/interview-preparation
==========================================================================================================
Coding platforms of international repute: for coding practice
1. https://www.hackerrank.com
2. https://www.codechef.com
3. https://leetcode.com
==========================================================================================================
1. https://www.tutorialspoint.com/python
2. https://www.javatpoint.com/python-tutorial
3. https://www.programiz.com/python-programming
4. https://www.geeksforgeeks.org/python-programming-language/
5. https://www.w3schools.com/python
6. https://onlinecourses.nptel.ac.in/noc22_cs26/preview
==========================================================================================================
Thanks.
Prof.BS
9550411738
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 22 of 22