-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathForGoodUnderstanding.py
213 lines (165 loc) · 5.5 KB
/
ForGoodUnderstanding.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
'''
What is Exception?
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.
'''
print(1/0) # Syntactically it's right, but do you think this will execute?
# print(name) # have we declared/defined before this line of code?
# What will be the output?
# print('2' + 5)
# To overcome the above examples, I'm creating method, which handles the exeptions in it.
# First example
def division():
try:
print(1/0)
except ZeroDivisionError:
print("why are you trying to divide a natural number with 0?")
except ValueError:
print("Value error man..")
except TimeoutError:
print("time out error sir..")
division()
# Second example
def showName():
try:
print(name)
except ZeroDivisionError:
print("why are you trying divide a natural number with 0?")
except ValueError:
print("Value error man..")
except TimeoutError:
print("time out error sir..")
except NameError:
print("You haven't defined any such variable btw")
# Stlyish way is..
except (RecursionError,NameError,TypeError, ZeroDivisionError) as e:
print("I catched.")
print("Unforu.. user has tried this, blah ")
# logger.log(e.messages)
pass
showName()
# Third Example
def addValues():
try:
print('2' + 'Sanjay' + 1232)
# except TypeError:
# print("I don't support this type.")
# except Exception:
# print("Master guy says, Something went wrong inside the code.")
# print("ERROR_CODE_SYMC_PO@$#:5533636")
except SanjayException:
print("Something")
addValues()
# Till now, we saw about predefined or system defined exceptions, isn't it?
# Think about writing our own exceptions?
# JFYI
'''
When we are developing a large Python program, it is a good practice to place all the user-defined
exceptions that our program raises in a separate file. Many standard modules do this. They define their
exceptions separately as exceptions.py or errors.py (generally but not always).
user-defined exception class can implement everything a normal class can do, but we generally make them simple and concise.
Most implementations declare a custom base class and derive others exception classes from this base class.
'''
# first example of user defined exception.
class SanjayException(Exception):
pass
import collections
import ExceptionalHandling
# class RamException():
# def m1(self):
# ExceptionalHandling.ForGoodUnderstanding
def evenOrOdd(number):
if type(number) is not int:
raise(SanjayException("input parameter is not in right format"))
# if (number % 2 == 0):
# return True
# else:
# return False
return True if number %2 ==0 else False
evenOrOdd('Sanjay')
# To go even deeper, here's the list of user defined exceptions.
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
class RamsException1010(ZeroDivisionError):
pass
# you need to guess this number
gloal_lucky_number = 10
# user guesses a number until he/she gets it right
while True:
try:
userGivenInput = int(input("Enter a number: "))
if userGivenInput < gloal_lucky_number:
raise ValueTooSmallError
elif userGivenInput > gloal_lucky_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()
except RamsZeroDivisionError:
print("Sory I cannot divide by Zero!")
raise(RamsException1010("Error message"))
print("Congratulations! You guessed it correctly.")
# Q & A ?
'''
Here's the overall predefined exception tree structure.
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StandardError
| +-- BufferError
| +-- ArithmeticError
| | +-- FloatingPointError
| | +-- OverflowError
| | +-- ZeroDivisionError
| +-- AssertionError
| +-- AttributeError
| +-- EnvironmentError
| | +-- IOError
| | +-- OSError
| | +-- WindowsError (Windows)
| | +-- VMSError (VMS)
| +-- EOFError
| +-- ImportError
| +-- LookupError
| | +-- IndexError
| | +-- KeyError
| +-- MemoryError
| +-- NameError
| | +-- UnboundLocalError
| +-- ReferenceError
| +-- RuntimeError
| | +-- NotImplementedError
| +-- SyntaxError
| | +-- IndentationError
| | +-- TabError
| +-- SystemError
| +-- TypeError
| +-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
'''