forked from joeyajames/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exception-handling.py
66 lines (50 loc) · 1.48 KB
/
exception-handling.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
# something more about try except
# basic syntax
'''
try:
code1
except:
some code that will execute if code 1 fails or raise some error
else:
this code is executed only if try was succesful i.e no error in code1
finally:
this code will execute in every situation if try fails or not
'''
filename = 'exception_data.txt'
# Outer try block catches file name or file doesn't exist errors.
try:
with open(filename) as fin:
for line in fin:
# print(line)
items = line.split(',')
total = 0
# Inner try bock catches integer conversion errors.
try:
for item in items:
num = int(item)
total += num
print('Total = ' + str(total))
except:
print('Error converting to integer. ', items)
except:
print('Error opening file. ' + filename)
finally:
print('This is our optional finally block. Code here will execute no matter what.')
# Second example: name Error type in except block; call function from try block.
def this_fails():
x = 1/0
try:
this_fails()
except ZeroDivisionError as err:
print('Handling run-time error:', err)
def divide_me(n):
x = 1/n
i = int(input('enter a number '))
try:
divide_me(i)
except Exception as e:
print(e) # this will print the error msg but don't kill the execution of program
else:
print('Your Code Run Successfully') # this will execute if divide_me(i) run sucessfully without an error
finally:
print('thanks') # this will execute in every condition