-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtry-exception.py
97 lines (81 loc) · 2.24 KB
/
try-exception.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
# example 1
# print(x)
try:
# This statement will raise an error, because x is not defined:
print(x)
except:
print("An exception occurred")
# Example 2: Print one message if the try block raises a NameError and another for other errors:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
# example 3: You can use the "else" eyword to define a block of code to be executed if no errors were raised:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
# example 4: The finally block, if specified, will be executed regardless if the try block raises an error or not.
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
finally:
print("This block will be executed regardless if the try block raises an error or not")
# Useful when Try to open and write to a file that is not writable:
try:
f = open("demofile.txt")
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
else:
f.close()
finally:
print("This block will be executed regardless if the try block raises an error or not")
# 10 * (1/0) # This statement will cause crash
try:
10 * (1 / 0)
except ZeroDivisionError:
print("Error: division by zero")
except:
print("something wrong")
# '2' + 2 # This statement will cause crash
try:
'2' + 2
except TypeError:
print("Error: Can't convert 'int' object to str implicitly")
except:
print("something wrong")
while True:
try:
v = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
except:
print("Something went wrong when writing to the file. Try again...")
else:
print("The value is {}".format(v))
finally:
print("This block will be executed regardless if the try block raises an error or not")
# '2' + 2 # This statement will cause crash
try:
'2' + 2
except (RuntimeError, TypeError, NameError):
pass
except:
print("something wrong")
finally:
print("Finally")
try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
raise
print("After 'raise'")