-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathErrorandException.py
More file actions
99 lines (76 loc) · 1.84 KB
/
ErrorandException.py
File metadata and controls
99 lines (76 loc) · 1.84 KB
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
#Example of try except block
def div(a,b):
try:
print(a/b)
except :
print("Error !")
print("Executed")
div(10,0) #--will give error--
#Zero Division Error
def div2(a,b):
try:
print(a/b)
except ZeroDivisionError:
print("Error : You were trying to divide by zero")
print("Executed")
div2(10,0)
#Value Error
try:
a=int("Amit")
except ZeroDivisionError:
print("Error : You were trying to divide by zero")
except ValueError:
print("Value Error Occured")
#Universal statement for finding Error
try:
print(10/0)
except Exception as e:
print(type(e)) #Zero division Error
#creating Custom Error and Exceptions
#-raise statement
try:
raise Exception("My Custom Error")
except Exception as e:
print(e)
#my Exception class
#Exception- base exception class
class MyException(Exception):
def __init__(self,message):
self.message=message
def __str__(self):
return self.message
try:
raise MyException("some Error")
except Exception as e:
print(e)
#----------#
print("------smarter way-----")
#Smarter way for writing Error and Exception-
# else:will always exceute if the try block didn't threw any error
# finally:will always execute
try:
print("Hello world")
print(10/0)
except:
print("Ok error occured")
else:
print("Woah")
finally:
#cleanup code or exiting code
print("bye bye world")
#----Trick question asked in interview----
print("------Trick Question------")
def func():
try:
return 1
except:
return 2
else:
return 3
finally:
return 4
#so here -
# > finally block will always be executed whether at any condition
# > else block will only be executed when try block fails
#-----with statement----
print("------with statement------")