Python Exception Handling PDF
Python Exception Handling PDF
Complete
Python
In
Simple Way
1 https://www.youtube.com/durgasoftware
EXCEPTION
HANDLING
STUDY MATERIAL
2 https://www.youtube.com/durgasoftware
In any programming language there are 2 types of errors are possible.
1) Syntax Errors
2) Runtime Errors
1) Syntax Errors:
The errors which occur 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.
Eg:
1) print(10/0) ZeroDivisionError: division by zero
2) print(10/"ten") TypeError: unsupported operand type(s) for /: 'int' and 'str'
3) 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
3 https://www.youtube.com/durgasoftware
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
Exception handling does not mean repairing exception. We have to define alternative way
to continue rest of the program normally.
Eg: For example our programming requirement is reading data from remote file locating
at London. At runtime if London file is not available then the program should not be
terminated abnormally. We have to provide local file to continue rest of the program
normally. This way of defining alternative is nothing but exception handling.
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?
4 https://www.youtube.com/durgasoftware
The rest of the program won't be executed.
1) print("Hello")
2) print(10/0)
3) print("Hi")
D:\Python_classes>py test.py
Hello
Traceback (most recent call last):
File "test.py", line 2, in <module>
print(10/0)
ZeroDivisionError: division by zero
Overflow Permission
Error Error
TimeOut
Error
5 https://www.youtube.com/durgasoftware
Every Exception in Python is a class.
All exception classes are child classes of BaseException.i.e every exception class
extends BaseException either directly or indirectly. Hence BaseException acts as root
for Python Exception Hierarchy.
Most of the times being a programmer we have to concentrate Exception and its child
classes.
Without try-except:
1) print("stmt-1")
2) print(10/0)
3) print("stmt-3")
Output
stmt-1
ZeroDivisionError: division by zero
Abnormal termination/Non-Graceful Termination
With try-except:
1) print("stmt-1")
2) try:
3) print(10/0)
4) except ZeroDivisionError:
5) print(10/2)
6) print("stmt-3")
Output
stmt-1
5.0
stmt-3
Normal termination/Graceful Termination
6 https://www.youtube.com/durgasoftware
Control Flow in try-except:
try:
stmt-1
stmt-2
stmt-3
except XXX:
stmt-4
stmt-5
Case-3: If an exception rose at stmt-2 and corresponding except block not matched
1, Abnormal Termination
Conclusions:
1) Within the try block if anywhere exception raised then rest of the try block won’t 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.
2) In addition to try block, there may be a chance of raising exceptions inside except and
finally blocks also.
3) If any statement which is not part of try block raises an exception then it is always
abnormal termination.
1) print(10/0)
2) except ZeroDivisionError as msg:
3) print("exception raised and its description is:",msg)
7 https://www.youtube.com/durgasoftware
try with Multiple except Blocks:
The way of handling exception is varied from exception to exception.Hence for every
exception type a seperate except block we have to provide. i.e try with multiple except
blocks is possible and recommended to use.
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.
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")
D:\Python_classes>py test.py
Enter First Number: 10
Enter Second Number: 2
5.0
D:\Python_classes>py test.py
Enter First Number: 10
Enter Second Number: 0
Can't Divide with Zero
D:\Python_classes>py test.py
Enter First Number: 10
Enter Second Number: ten
please provide int value only
8 https://www.youtube.com/durgasoftware
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.
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")
D:\Python_classes>py test.py
Enter First Number: 10
Enter Second Number: 0
ArithmeticError
except (Exception1,Exception2,exception3,..): OR
except (Exception1,Exception2,exception3,..) as msg :
Parentheses are mandatory and this group of exceptions internally considered as tuple.
1) try:
2) x=int(input("Enter First Number: "))
3) y=int(input("Enter Second Number: "))
4) print(x/y)
5) except (ZeroDivisionError,ValueError) as msg:
6) print("Plz Provide valid numbers only and problem is: ",msg)
D:\Python_classes>py test.py
Enter First Number: 10
Enter Second Number: 0
Plz Provide valid numbers only and problem is: division by zero
D:\Python_classes>py test.py
Enter First Number: 10
Enter Second Number: ten
Plz Provide valid numbers only and problem is: invalid literal for int() with b are 10: 'ten'
9 https://www.youtube.com/durgasoftware
Default except Block:
We can use default except block to handle any type of exceptions.
In default except block generally we can print normal error messages.
Syntax:
except:
statements
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")
D:\Python_classes>py test.py
Enter First Number: 10
Enter Second Number: 0
ZeroDivisionError:Can't divide with zero
D:\Python_classes>py test.py
Enter First Number: 10
Enter Second Number: ten
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.
1) try:
2) print(10/0)
3) except:
4) print("Default Except")
5) except ZeroDivisionError:
6) print("ZeroDivisionError")
10 https://www.youtube.com/durgasoftware
4) except (ZeroDivisionError,ValueError) as msg:
5) except :
finally Block:
☕ 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.
☕ It is not recommended to maintain clean up code inside except block, because if there
is no exception then except block won't be executed.
☕ Hence we required some place to maintain clean up code which should be executed
always irrespective of whether exception raised or not raised and whether exception
handled or not handled. Such type of best place is nothing but finally block.
☕ Hence the main purpose of finally block is to maintain clean up code.
try:
Risky Code
except:
Handling Code
finally:
Cleanup code
The speciality of finally block is it will be executed always whether exception raised or not
raised and whether exception handled or not handled.
1) try:
2) print("try")
3) except:
4) print("except")
5) finally:
6) print("finally")
Output
try
finally
1) try:
2) print("try")
3) print(10/0)
11 https://www.youtube.com/durgasoftware
4) except ZeroDivisionError:
5) print("except")
6) finally:
7) print("finally")
Output
try
except
finally
1) try:
2) print("try")
3) print(10/0)
4) except NameError:
5) print("except")
6) finally:
7) print("finally")
Output
try
finally
ZeroDivisionError: division by zero(Abnormal Termination)
*** Note: There is only one situation where finally block won't be executed ie whenever
we are using os._exit(0) function.
Whenever we are using os._exit(0) function then Python Virtual Machine itself will be
shutdown.In this particular case finally won't be executed.
1) imports
2) try:
3) print("try")
4) os._exit(0)
5) except NameError:
6) print("except")
7) finally:
8) print("finally")
Output: try
12 https://www.youtube.com/durgasoftware
Note:
os._exit(0)
Where 0 represents status code and it indicates normal termination
There are multiple status codes are possible.
Case-2: If an exception raised at stmt2 and the corresponding except block matched
1,4,5,6 Normal Termination
Case-3: If an exception raised at stmt2 but the corresponding except block not matched
1,5 Abnormal Termination
Case-4:If an exception raised at stmt4 then it is always abnormal termination but before
that finally block will be executed.
13 https://www.youtube.com/durgasoftware
except:
--------------
--------------
--------------
------------
except:
-----------
-----------
-----------
General Risky code we have to take inside outer try block and too much risky code we
have to take inside inner try block. Inside Inner try block if an exception raised then inner
except block is responsible to handle. If it is unable to handle then outer except block is
responsible to handle.
1) try:
2) print("outer try block")
3) try:
4) print("Inner try block")
5) print(10/0)
6) except ZeroDivisionError:
7) print("Inner except block")
8) finally:
9) print("Inner finally block")
10) except:
11) print("outer except block")
12) finally:
13) print("outer finally block")
Output
outer try block
Inner try block
Inner except block
Inner finally block
outer finally block
14 https://www.youtube.com/durgasoftware
stmt-5
stmt-6
except X:
stmt-7
finally:
stmt-8
stmt-9
except Y:
stmt-10
finally:
stmt-11
stmt-12
Case-2: If an exception raised at stmt-2 and the corresponding except block matched
1,10,11,12 Normal Termination
Case-3: If an exceptiion raised at stmt-2 and the corresponding except block not matched
1,11,Abnormal 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-8: If an exception raised at stmt-7 and corresponding except block not matched
1,2,3,.,.,.,8,11,Abnormal Termination
Case-10: If an exception raised at stmt-8 and corresponding except block not matched
1,2,3,.,.,.,.,11,Abnormal Termination
15 https://www.youtube.com/durgasoftware
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
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.
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.
16 https://www.youtube.com/durgasoftware
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
try:
1
print("try")
except:
2
print("Hello")
else:
3
print("Hello")
finally:
4
print("Hello")
try:
print("try")
5
except: √
print("except")
try:
print("try")
6
finally: √
print("finally")
17 https://www.youtube.com/durgasoftware
try:
print("try")
except:
7
print("except") √
else:
print("else")
try:
print("try")
8
else:
print("else")
try:
print("try")
else:
9
print("else")
finally:
print("finally")
try:
print("try")
except XXX:
10
print("except-1") √
except YYY:
print("except-2")
try:
print("try")
except :
print("except-1")
11
else:
print("else")
else:
print("else")
try:
print("try")
except :
print("except-1")
12
finally:
print("finally")
finally:
print("finally")
try:
print("try")
13
print("Hello")
except:
18 https://www.youtube.com/durgasoftware
print("except")
try:
print("try")
except:
14 print("except")
print("Hello")
except:
print("except")
try:
print("try")
except:
15 print("except")
print("Hello")
finally:
print("finally")
try:
print("try")
except:
16 print("except")
print("Hello")
else:
print("else")
try:
print("try")
except:
print("except")
17
try: √
print("try")
except:
print("except")
try:
print("try")
except:
print("except")
18
try: √
print("try")
finally:
print("finally")
try:
print("try")
19
except: √
print("except")
19 https://www.youtube.com/durgasoftware
if 10>20:
print("if")
else:
print("else")
try:
print("try")
try:
print("inner try")
except:
20
print("inner except block") √
finally:
print("inner finally block")
except:
print("except")
try:
print("try")
except:
print("except")
21 try:
print("inner try")
√
except:
print("inner except block")
finally:
print("inner finally block")
try:
print("try")
except:
print("except")
finally:
22 try:
print("inner try")
√
except:
print("inner except block")
finally:
print("inner finally block")
try:
print("try")
except:
23 print("except")
try:
print("try")
else:
20 https://www.youtube.com/durgasoftware
print("else")
try:
print("try")
try:
24
print("inner try")
except:
print("except")
try:
print("try")
else:
print("else")
25
except:
print("except")
finally:
print("finally")
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 inbuilt exceptions.
The exceptions which are raised automatically by Python virtual machine whenver a
particular event occurs are called pre defined exceptions.
Eg 2: Whenever we are trying to convert input value to int type and if input value is
not int value then Python will raise ValueError automatically
x=int("ten") ValueError
21 https://www.youtube.com/durgasoftware
Programmer is responsible to define these exceptions and Python not having any idea
about these. Hence we have to raise explicitly based on our requirement by using
"raise" keyword.
Eg:
InSufficientFundsException
InvalidInputException
TooYoungException
TooOldException
Syntax:
class classname(predefined exception class name):
def __init__(self,arg):
self.msg=arg
1) class TooYoungException(Exception):
2) def __init__(self,arg):
3) self.msg=arg
1) class TooYoungException(Exception):
2) def __init__(self,arg):
3) self.msg=arg
4)
5) class TooOldException(Exception):
6) def __init__(self,arg):
7) self.msg=arg
8)
9) age=int(input("Enter Age:"))
10) if age>60:
11) raise TooYoungException("Plz wait some more time you will get best match soon!!!")
12) elif age<18:
13) raise TooOldException("Your age already crossed marriage age...no chance of
getting marriage")
14) else:
15) print("You will get match details soon by email!!!")
22 https://www.youtube.com/durgasoftware
D:\Python_classes>py test.py
Enter Age:90
__main__.TooYoungException: Plz wait some more time you will get best match soon!!!
D:\Python_classes>py test.py
Enter Age:12
__main__.TooOldException: Your age already crossed marriage age...no chance of g
etting marriage
D:\Python_classes>py test.py
Enter Age:27
You will get match details soon by email!!!
Note: raise keyword is best suitable for customized exceptions but not for pre defined
exceptions
23 https://www.youtube.com/durgasoftware