Skip to content

Commit e437c96

Browse files
committed
Python files for understanding exceptional handling
1 parent d1000be commit e437c96

File tree

2 files changed

+218
-0
lines changed

2 files changed

+218
-0
lines changed

ExceptionalHandling/EHFinally.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
2+
3+
# Important point to be noted.
4+
5+
# finally block is always executed after leaving the try statement.
6+
# In case if some exception was not handled by except block, it is re-raised after execution of finally block.
7+
# finally block is used to deallocate the system resources.
8+
# One can use finally just after try without using except block, but no exception is handled in that case.
9+
10+
# here's the sample exercise for understanding `finally` keyword in python
11+
12+
try:
13+
inFromUser = int(input("Hello user, give me a integer input: "))
14+
k = 5//inFromUser # raises divide by zero exception.
15+
print(k)
16+
17+
# handles zerodivision exception
18+
except ZeroDivisionError:
19+
print("Can't divide by zero")
20+
except TypeError:
21+
print("Given in put is not in a right datatype")
22+
23+
finally:
24+
# this block is always executed
25+
# regardless of exception generation.
26+
print('This is always executed')
27+
28+
29+
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
2+
'''
3+
What is Exception?
4+
5+
Errors detected during execution are called exceptions, if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it.
6+
7+
'''
8+
9+
# print(1/0) # Syntactically it's right, but do you think this will execute?
10+
11+
# print(name) # have we declared/defined before this line of code?
12+
13+
# What will be the output?
14+
15+
# print('2' + 5)
16+
17+
18+
# To overcome the aboev examples, I'm creating method, which handles the exeptions in it.
19+
20+
# First example
21+
22+
def division():
23+
try:
24+
print(1/0)
25+
except ZeroDivisionError:
26+
print("why are you trying divide a natural number with 0?")
27+
except ValueError:
28+
print("Value error man..")
29+
except TimeoutError:
30+
print("time out error sir..")
31+
32+
division()
33+
34+
# Second example
35+
36+
def showName():
37+
try:
38+
print(name)
39+
except ZeroDivisionError:
40+
print("why are you trying divide a natural number with 0?")
41+
except ValueError:
42+
print("Value error man..")
43+
except TimeoutError:
44+
print("time out error sir..")
45+
except NameError:
46+
print("You haven't defined any such variable btw")
47+
# Stlyish way is..
48+
except (RecursionError,NameError,TypeError, ZeroDivisionError):
49+
print("I catched.")
50+
pass
51+
52+
showName()
53+
54+
# Third Example
55+
56+
def addValues():
57+
try:
58+
print('2' + 'Sanjay' + 1232)
59+
# except TypeError:
60+
# print("I don't support this type.")
61+
except Exception:
62+
print("Master guy says, Something went wrong inside the code.")
63+
64+
addValues()
65+
66+
# Till now, we saw about predefined or system defined exceptions, isn't it?
67+
# Think about writing our own exceptions?
68+
69+
# JFYI
70+
71+
'''
72+
When we are developing a large Python program, it is a good practice to place all the user-defined
73+
exceptions that our program raises in a separate file. Many standard modules do this. They define their
74+
exceptions separately as exceptions.py or errors.py (generally but not always).
75+
76+
77+
ser-defined exception class can implement everything a normal class can do, but we generally make them simple and concise.
78+
Most implementations declare a custom base class and derive others exception classes from this base class.
79+
'''
80+
81+
# first example of user defined exception.
82+
class SanjayException(Exception):
83+
pass
84+
85+
86+
def evenOrOdd(number):
87+
if type(number) is not int:
88+
raise(SanjayException("input parameter is not in right format"))
89+
return True if number %2 ==0 else False
90+
91+
evenOrOdd('Sanjay')
92+
93+
94+
# To go even deeper, here's the list of user defined exceptions.
95+
96+
class Error(Exception):
97+
"""Base class for other exceptions"""
98+
pass
99+
100+
101+
class ValueTooSmallError(Error):
102+
"""Raised when the input value is too small"""
103+
pass
104+
105+
106+
class ValueTooLargeError(Error):
107+
"""Raised when the input value is too large"""
108+
pass
109+
110+
111+
# you need to guess this number
112+
gloal_lucky_number = 10
113+
114+
# user guesses a number until he/she gets it right
115+
while True:
116+
try:
117+
userGivenInput = int(input("Enter a number: "))
118+
if userGivenInput < gloal_lucky_number:
119+
raise ValueTooSmallError
120+
elif userGivenInput > gloal_lucky_number:
121+
raise ValueTooLargeError
122+
break
123+
except ValueTooSmallError:
124+
print("This value is too small, try again!")
125+
print()
126+
except ValueTooLargeError:
127+
print("This value is too large, try again!")
128+
print()
129+
130+
print("Congratulations! You guessed it correctly.")
131+
132+
133+
# Q & A ?
134+
135+
136+
'''
137+
Here's the overall predefined exception tree structure.
138+
139+
BaseException
140+
+-- SystemExit
141+
+-- KeyboardInterrupt
142+
+-- GeneratorExit
143+
+-- Exception
144+
+-- StopIteration
145+
+-- StandardError
146+
| +-- BufferError
147+
| +-- ArithmeticError
148+
| | +-- FloatingPointError
149+
| | +-- OverflowError
150+
| | +-- ZeroDivisionError
151+
| +-- AssertionError
152+
| +-- AttributeError
153+
| +-- EnvironmentError
154+
| | +-- IOError
155+
| | +-- OSError
156+
| | +-- WindowsError (Windows)
157+
| | +-- VMSError (VMS)
158+
| +-- EOFError
159+
| +-- ImportError
160+
| +-- LookupError
161+
| | +-- IndexError
162+
| | +-- KeyError
163+
| +-- MemoryError
164+
| +-- NameError
165+
| | +-- UnboundLocalError
166+
| +-- ReferenceError
167+
| +-- RuntimeError
168+
| | +-- NotImplementedError
169+
| +-- SyntaxError
170+
| | +-- IndentationError
171+
| | +-- TabError
172+
| +-- SystemError
173+
| +-- TypeError
174+
| +-- ValueError
175+
| +-- UnicodeError
176+
| +-- UnicodeDecodeError
177+
| +-- UnicodeEncodeError
178+
| +-- UnicodeTranslateError
179+
+-- Warning
180+
+-- DeprecationWarning
181+
+-- PendingDeprecationWarning
182+
+-- RuntimeWarning
183+
+-- SyntaxWarning
184+
+-- UserWarning
185+
+-- FutureWarning
186+
+-- ImportWarning
187+
+-- UnicodeWarning
188+
+-- BytesWarning
189+
'''

0 commit comments

Comments
 (0)