Skip to content

Commit 8818f0a

Browse files
committed
Add illustration of error handling
1 parent 1085017 commit 8818f0a

File tree

5 files changed

+46
-0
lines changed

5 files changed

+46
-0
lines changed

source-code/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,4 @@ was used to develop it.
3131
structures.
3232
1. `code-organization`: illustration of how to organize code in packages
3333
and modules.
34+
1. `error-handling`: simple illustration of error handling.

source-code/error-handling/README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# Error handling
2+
3+
Illustrations of error handling.
4+
5+
## What is it?
6+
7+
1. `simple.py`: Python scripts that illustrates some
8+
ways ot handle errors.
9+
1. `data.txt`: data file to use as input.
10+
1. `data_not_ok.txt`: incorrect data file to use as input.

source-code/error-handling/data.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
3.7
2+
3.3
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
3.7
2+
5.1
3+
some_string
4+
5.2

source-code/error-handling/simple.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#!/usr/bin/env python
2+
3+
import sys
4+
5+
ARG_ERROR = 1
6+
FILE_ERROR = 2
7+
DATA_ERROR = 3
8+
9+
def sum_numbers(file):
10+
total = 0
11+
for line in file:
12+
total += float(line)
13+
return total
14+
15+
16+
if __name__ == '__main__':
17+
if len(sys.argv) < 2:
18+
print('### error: no argument given', file=sys.stderr)
19+
sys.exit(ARG_ERROR)
20+
file_name = sys.argv[1]
21+
try:
22+
file = open(file_name, 'r')
23+
print(sum_numbers(file))
24+
except IOError as e:
25+
print(f'### IO Error on {e.filename}: {e.strerror}')
26+
sys.exit(FILE_ERROR)
27+
except ValueError:
28+
print(f'### Data Error on {file_name}: should contain only numbers')
29+
sys.exit(DATA_ERROR)

0 commit comments

Comments
 (0)