Chapter 13 Python
Chapter 13 Python
******************Chapter-13***********************
**************************************************
***************13.Exception Handling ***********:-
………………………………………………………………………………………………
In any programming language there are 2 types of errors are
possible.
1. Syntax Errors
2. Runtime Errors
1. Syntax Errors:-
.................................
The errors which occurs because of invalid syntax are
called syntax errors.
Eg 1:
x=10
if x==10
print("Hello")
Eg 2: print "Hello"
………………………………………………..
SyntaxError: Missing parentheses in call to 'print'
……………………………………………………………………………………………
Note: Programmer is responsible to correct these syntax
errors. Once all syntax errors are corrected then only
program execution will be started.
………………………………………………………………………………………………
2. Runtime Errors:-
……………………………………….
Also known as exceptions. While executing the program
if something goes wrong because of end user input or
programming logic or memory problems etc then we will
get Runtime Errors.
……………………………………………………………….
x=int(input("Enter Number:"))
print(x)
D:\Python_classes>py test.py
Enter Number:ten
ValueError: invalid literal for int() with base 10: 'ten'
…………………………………………………………………………………
Note: Exception Handling concept applicable for Runtime
Errors but not for syntax errors
…………………………………………………………………………..
What is Exception:
…………………………………………………………
An unwanted and unexpected event that disturbs normal
flow of program is called exception.
Eg:
ZeroDivisionError
TypeError
ValueError
FileNotFoundError
EOFError
SleepingError
TyrePuncturedError
………………………………………………………………….
It is highly recommended to handle exceptions. The main
objective of exception handling is Graceful Termination of
the program(i.e we should not block our resources and we
should not miss anything)
try:
read data from remote file locating at london
except FileNotFoundError:
use local file and continue rest of the program normally
Q. What is an Exception?
Q. What is the purpose of Exception Handling?
Q. What is the meaning of Exception Handling?
………………………………………………………………………………………………
Default Exception Handing in Python: -
…………………………………………………………………
Every exception in Python is an object. For every exception
type the corresponding classes are available.
try:
stmt-1
stmt-2
stmt-3
except XXX:
stmt-4
stmt-5
……………………………………………………………………….
case-1: If there is no exception
1,2,3,5 and Normal Termination
………………………………………………………………..
case-2: If an exception raised at stmt-2 and corresponding
except block matched
1,4,5 Normal Termination
……………………………………………………………………..
case-3: If an exception raised at stmt-2 and corresponding
except block not matched
1, Abnormal Termination
………………………………………………………………………………………..
case-4: If an exception raised at stmt-4 or at stmt-5 then it is
always abnormal termination.
……………………………………………………………………………………
*************Conclusions:*******************:-
…………………………………………………………………………………..
1. within the try block if anywhere exception raised then rest
of the try block wont be executed eventhough we handled
that exception. Hence we have to take only risky code inside
try block and length of the try block should be as less as
possible.
Eg:
try:
-------
-------
-------
except ZeroDivisionError:
perform alternative
arithmetic operations
…………………………………………………………………………………………
except FileNotFoundError:
use local file instead of remote file
If try with multiple except blocks available then based on
raised exception the corresponding except block will be
executed.
……………………………………………………………………………….
Eg:
1) try:
2) x=int(input("Enter First Number: "))
3) y=int(input("Enter Second Number: "))
4) print(x/y)
5) except ZeroDivisionError :
6) print("Can't Divide with Zero")
7) except ValueError:
8) print("please provide int value only")
9)
10) D:\Python_classes>py test.py
11) Enter First Number: 10
12) Enter Second Number: 2
13) 5.0
14)
15) D:\Python_classes>py test.py
16) Enter First Number: 10
17) Enter Second Number: 0
18) Can't Divide with Zero
19)
20) D:\Python_classes>py test.py
21) Enter First Number: 10
22) Enter Second Number: ten
23) please provide int value only
…………………………………………………………………………
If try with multiple except blocks available then the order of
these except blocks is important .Python interpreter will
always consider from top to bottom until matched except
block identified.
…………………………………………………………………………..
Eg:
1) try:
2) x=int(input("Enter First Number: "))
3) y=int(input("Enter Second Number: "))
4) print(x/y)
5) except ArithmeticError :
6) print("ArithmeticError")
7) except ZeroDivisionError:
8) print("ZeroDivisionError")
9)
10) D:\Python_classes>py test.py
11) Enter First Number: 10
12) Enter Second Number: 0
13) ArithmeticError
………………………………………………………………………………………………
**Single except block that can handle multiple exceptions:
……………………………………………………………..
We can write a single except block that can handle multiple
different types of exceptions.
except (Exception1,Exception2,exception3,..): or
except (Exception1,Exception2,exception3,..) as msg :
Syntax:
except:
statements
……………………………………………………………
Eg:
1) try:
2) x=int(input("Enter First Number: "))
3) y=int(input("Enter Second Number: "))
4) print(x/y)
5) except ZeroDivisionError:
6) print("ZeroDivisionError:Can't divide with zero")
7) except:
8) print("Default Except:Plz provide valid input only")
9)
10) D:\Python_classes>py test.py
11) Enter First Number: 10
12) Enter Second Number: 0
13) ZeroDivisionError:Can't divide with zero
14)
15) D:\Python_classes>py test.py
16) Enter First Number: 10
17) Enter Second Number: ten
18) Default Except:Plz provide valid input only
………………………………………………………………………………………….
***Note: If try with multiple except blocks available then
default except block should be last,otherwise we will get
SyntaxError.
……………………………………………………………………………………….
Eg:
1) try:
2) print(10/0)
3) except:
4) print("Default Except")
5) except ZeroDivisionError:
6) print("ZeroDivisionError")
7)
8) SyntaxError: default 'except:' must be last
………………………………………………………………………………
Note:
The following are various possible combinations of except
blocks
1. except ZeroDivisionError:
1. except ZeroDivisionError as msg:
3. except (ZeroDivisionError,ValueError) :
4. except (ZeroDivisionError,ValueError) as msg:
5. except :
…………………………………………………………………………..
finally block:
……………………………….
1. It is not recommended to maintain clean up code(Resource
Deallocating Code or Resource Releasing code) inside try
block because there is no guarentee for the execution of
every statement inside try block always.
try:
Risky Code
except:
Handling Code
finally:
Cleanup code
………………………………………………………………………………………………
.
case-3: If an exceptiion raised at stmt-2 and the
corresponding except block not matched 1,11,Abnormal
Termination
……………………………………………………………………………………………
case-4: If an exception raised at stmt-5 and inner except
block matched 1,2,3,4,7,8,9,11,12 Normal Termination
………………………………………………………………………………….
case-5: If an exception raised at stmt-5 and inner except
block not matched but outer except block matched
1,2,3,4,8,10,11,12,Normal Termination
…………………………………………………………………………..
case-6:If an exception raised at stmt-5 and both inner and
outer except blocks are not matched
1,2,3,4,8,11,Abnormal Termination
…………………………………………………………………………………………
case-7: If an exception raised at stmt-7 and corresponding
except block matched 1,2,3,.,.,.,8,10,11,12,Normal
Termination
…………………………………………………………………………………..
case-8: If an exception raised at stmt-7 and corresponding
except block not matched 1,2,3,.,.,.,8,11,Abnormal
Termination
……………………………………………………………………………………..
case-9: If an exception raised at stmt-8 and corresponding
except block matched 1,2,3,.,.,.,.,10,11,12 Normal
Termination
…………………………………………………………………………………………….
case-10: If an exception raised at stmt-8 and corresponding
except block not matched 1,2,3,.,.,.,.,11,Abnormal
Termination
…………………………………………………………………………………………
case-11: If an exception raised at stmt-9 and corresponding
except block matched 1,2,3,.,.,.,.,8,10,11,12,Normal
Termination
…………………………………………………………………………………………
case-12: If an exception raised at stmt-9 and corresponding
except block not matched 1,2,3,.,.,.,.,8,11,Abnormal
Termination
………………………………………………………………………………
case-13: If an exception raised at stmt-10 then it is always
abonormal termination but before abnormal termination
finally block(stmt-11) will be executed.
…………………………………………………………………………………………..
case-14: If an exception raised at stmt-11 or stmt-12 then it is
always abnormal termination.
……………………………………………………………………………………………
Note: If the control entered into try block then compulsary
finally block will be executed. If the control not entered into
try block then finally block won't be executed.
…………………………………………………………………………………………….
*********else block with try-except-finally:*********:-
……………………………………………………………………………………….
We can use else block with try-except-finally blocks. else
block will be executed if and only if there are no exceptions
inside try block.
try:
Risky Code
except:
will be executed if exception inside try
else:
will be executed if there is no exception inside try finally:
will be executed whether exception raised or not raised
and handled or not handled
………………………………………………………………………………………
Eg:
try:
print("try")
print(10/0)--->1
except:
print("except")
else:
print("else")
finally:
print("finally")
…………………………………………………………………………………
If we comment line-1 then else block will be executed b'z
there is no exception inside try. In this case the output is:
……………………………………………………………
try
else
finally
……………………………………………………………………………..
If we are not commenting line-1 then else block won't be
executed b'z there is exception inside try block. In this case
output is:
…………………………………………………………………………………
try
except
finally
……………………………………………………………………………………..
Various possible combinations of try-except-else-finally: -
………………………………………………………………………………………….
1. Whenever we are writing try block, compulsory we should
write except or finally block.i.e without except or finally block
we cannot write try block.
……………………………………………………………………………………………
………………………………………………………………………………………………
……………………………………………………………………………………………
……………………………………………………………………………………………
………………………………………………………………………………………………
……………………………………………………………………………………………
*************Types of Exceptions:**************:-
………………………………………………………………………………………….
In Python there are 2 types of exceptions are possible.
1. Predefined Exceptions
2. User Definded Exceptions
…………………………………………………………………………………………..
1. Predefined Exceptions:
……………………………………………
Also known as in-built exceptions
x=int("ten")===>ValueError
………………………………………………………………………………………………
2. User Defined Exceptions:
……………………………………………….
Also known as Customized Exceptions or Programatic
Exceptions
………………………………………………………………………………………………
Eg:
InSufficientFundsException
InvalidInputException
TooYoungException
TooOldException
…………………………………………………………………………………
******How to Define and Raise Customized Exceptions:**:-
………………………………………………………………………………………..
Every exception in Python is a class that extends Exception
class either directly or indirectly.
……………………………………………..
Syntax:
class classname(predefined exception class name):
def __init__(self,arg):
self.msg=arg
Eg:
1) class TooYoungException(Exception):
2) def __init__(self,arg):
3) self.msg=arg
…………………………………………………………………………
TooYoungException is our class name which is the child class
of Exception
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
……………………………………………………………………
# our main program
# user guesses a number until he/she gets it right
while True:
try:
i_num = int(input("Enter a number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
print()
except ValueTooLargeError:
print("This value is too large, try again!")
print()
table
1. CRITICAL==>50==>Represents a very serious problem that
needs high attention
2. ERROR===>40===>Represents a serious error
3. WARNING==>30==>Represents a warning message, some
caution needed. It is alert to the programmer
4. INFO===>20===>Represents a message with some
important information
5. DEBUG===>10==>Represents a message with debugging
information
6. NOTSET==>0==>Rrepresents that the level is not set.
logging.basicConfig(filename='log.txt',level=logging.WARNIN
G)
The above line will create a file log.txt and we can store
either WARNING level or higher level messages to that file.
………………………………………………………..
log.txt:
1) DEBUG:root:This is debug message
2) INFO:root:This is info message
3) WARNING:root:This is warning message
4) ERROR:root:This is error message
5) CRITICAL:root:This is critical message
………………………………………………………………………………………………
Note: We can format log messages to include date and time,
ip address of the client etc at advanced level.
………………………………………………………………………………………….
***How to write Python program exceptions to the log file:
…………………………………………………………………………………..
By using the following function we can write exceptions
information to the log file.
logging.exception(msg)
……………………………………………………………………………………….
Q. Python Program to write exception information to the log
file
1) import logging
2)logging.basicConfig(filename='mylog.txt',level=logging.INF
O)
3) logging.info("A New request Came:")
4) try:
5) x=int(input("Enter First Number: "))
6) y=int(input("Enter Second Number: "))
7) print(x/y)
8) except ZeroDivisionError as msg:
9) print("cannot divide with zero")
10) logging.exception(msg)
11) except ValueError as msg:
12) print("Enter only int values")
13) logging.exception(msg)
14) logging.info("Request Processing Completed")
15)
16)
17) D:\Python_classes>py test.py
18) Enter First Number: 10
19) Enter Second Number: 2
20) 5.0
21)
22) D:\Python_classes>py test.py
23) Enter First Number: 10
24) Enter Second Number: 0
25) cannot divide with zero
26)
27) D:\Python_classes>py test.py
28) Enter First Number: 10
29) Enter Second Number: ten
30) Enter only int values
…………………………………………………………………………………..
mylog.txt:
1) INFO:root:A New request Came:
2) INFO:root:Request Processing Completed
3) INFO:root:A New request Came:
4) ERROR:root:division by zero
5) Traceback (most recent call last):
6) File "test.py", line 7, in <module>
7) print(x/y)
8) ZeroDivisionError: division by zero
9) INFO:root:Request Processing Completed
10) INFO:root:A New request Came:
11) ERROR:root:invalid literal for int() with base 10: 'ten'
12) Traceback (most recent call last):
13) File "test.py", line 6, in <module>
14) y=int(input("Enter Second Number: "))
15) ValueError: invalid literal for int() with base 10: 'ten'
16) INFO:root:Request Processing Completed
…………………………………………………………………………………………..
1. Simple Version
2. Augmented Version
……………………………………………………………..
1. Simple Version:
assert conditional_expression
…………………………………………………………
2. Augmented Version:
assert conditional_expression,message
………………………………………………………………
conditional_expression will be evaluated and if it is true then
the program will be continued. If it is false then the program
will be terminated by raising AssertionError. By seeing
AssertionError, programmer can analyze the code and can fix
the problem.
………………………………………………..
Eg:
1) def squareIt(x):
2) return x**x
3) assert squareIt(2)==4,"The square of 2 should be 4"
4) assert squareIt(3)==9,"The square of 3 should be 9"
5) assert squareIt(4)==16,"The square of 4 should be 16"
6) print(squareIt(2))
7) print(squareIt(3))
8) print(squareIt(4))
9)
10) D:\Python_classes>py test.py
11) Traceback (most recent call last):
12) File "test.py", line 4, in <module>
13) assert squareIt(3)==9,"The square of 3 should be 9"
14) AssertionError: The square of 3 should be 9
15)
16) def squareIt(x):
17) return x*x
18) assert squareIt(2)==4,"The square of 2 should be 4"
19) assert squareIt(3)==9,"The square of 3 should be 9"
20) assert squareIt(4)==16,"The square of 4 should be 16"
21) print(squareIt(2))
22) print(squareIt(3))
23) print(squareIt(4))
24)
25) Output
26) 4
27) 9
28) 16
………………………………………………………………………………………….
******Exception Handling vs Assertions:**********:-
……………………………………………………………………………….
Assertions concept can be used to alert programmer to
resolve development time errors.