Skip to content

Commit 95c7d8b

Browse files
author
ashegde
committed
feat(examples): errors and handling
1 parent ed40f35 commit 95c7d8b

File tree

6 files changed

+49
-0
lines changed

6 files changed

+49
-0
lines changed

codes/session_6/errorEg1.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Open terminal > python3 errorEg1.py
2+
# Start typing below commands and see the output
3+
4+
while True:
5+
try:
6+
x = int(input('Please enter a number: '))
7+
break
8+
except ValueError:
9+
print('Invalid number, please try again')

codes/session_6/errorEg2.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Open terminal > python3 errorEg2.py
2+
# Start typing below commands and see the output
3+
4+
import sys
5+
6+
for arg in sys.argv[1:]:
7+
try:
8+
f = open(arg, 'r')
9+
print(f.read())
10+
except OSError:
11+
print('[OS error]: ', arg)
12+
else:
13+
print(arg, 'has', len(f.readline()), 'lines')
14+
f.close()

codes/session_6/errorEg3.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
def thisWillFail():
2+
x = 1 / 0
3+
4+
try:
5+
thisWillFail()
6+
except ZeroDivisionError as err:
7+
print('Handling runtime error: ', err)

codes/session_6/errorEg4.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
try:
2+
raise NameError('Hi There! I am raising an error!')
3+
except NameError:
4+
print('An exception occured!')
5+
raise

codes/session_6/errorEg5.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
def divide(x, y):
2+
try:
3+
result = x / y
4+
except ZeroDivisionError:
5+
print('Division by zero!')
6+
else:
7+
print('result is ', result)
8+
finally:
9+
print('executing finally clause')
10+
11+
divide(45, 5)
12+
13+
divide(45, 0)

codes/session_6/hello.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Hello World!

0 commit comments

Comments
 (0)