Nearby lessons
72 of 108Python - Try Except
Detailed Tutorial Notes
Python's Exception Hierarchy
Every Exception in Python is a class.
All exception classes are child classes of BaseException.i.e every exception class extendsBaseException 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.
Customized Exception Handling by using try-except:
It is highly recommended to handle exceptions.
The code which may raise exception is called risky code and we have to take risky code
inside try block. The corresponding handling code we have to take inside except block.
Attribute
Error
Arithmetic
Error
EOF
Error
Name
Error
Lookup
Error
OS
Error
Type
Error
Value
Error
BaseException
Exception KeyboardInterrupt SystemExit GeneratorExit
ZeroDivision
Error
FloatingPoint
Error
Overflow
Error
Index
Error
Key
Error
FileNotFound
Error
Interrupted
Error
Permission
Error
TimeOut
Error
try:
Risky Code
except XXX:
Handling code/Alternative Code
without try-except:
main.py
1. print("stmt-1")4.
- Output
- stmt-1
- ZeroDivisionError: division by zero Abnormal termination/Non-Graceful Termination with try-except:
- try:
3. print(10/0)- except ZeroDivisionError:
main.py
1. print(10/0)
7.
- Output
- stmt-1
- 5.0
- stmt-3 Normal termination/Graceful Termination Control Flow in try-except: 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:
- 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.
- In addition to try block,there may be a chance of raising exceptions inside except and finally blocks also.
- If any statement which is not part of try block raises an exception then it is always abnormal termination. How to print exception information: try:
- except ZeroDivisionError as msg:
main.py
try:
x=int(input("Enter First Number: "))
y=int(input("Enter Second Number: "))
print(x/y)
except ZeroDivisionError :
print("Can't Divide with Zero")
except ValueError:
print("please provide int value only")4.
- Output exception raised and its description is: division by zero 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. Eg:
9)
10) D:\Python_classes>py test.py
11) Enter First Number: 10
12) Enter Second Number: 2
13) 5.014)
15) D:\Python_classes>py test.py
16) Enter First Number: 10
17) Enter Second Number: 0
18) Can't Divide with Zero19)
20) D:\Python_classes>py test.py
21) Enter First Number: 10
22) Enter Second Number: ten
23) please provide int value onlyIf 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) ArithmeticErrorSingle 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 :
Parenthesis are mandatory and this group of exceptions internally considered as tuple.
Eg:
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)7)
8) D:\Python_classes>py test.py
9) Enter First Number: 10
10) Enter Second Number: 0
11) Plz Provide valid numbers only and problem is: division by zero12)
13) D:\Python_classes>py test.py
14) Enter First Number: 10
15) Enter Second Number: ten
16) Plz Provide valid numbers only and problem is: invalid literal for int() with b
17) ase 10: 'ten'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
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 zero14)
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 lastNote:
The following are various possible combinations of except blocks
- except ZeroDivisionError:
- except ZeroDivisionError as msg:
- except (ZeroDivisionError,ValueError) :
- except (ZeroDivisionError,ValueError) as msg:
- 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.