File tree Expand file tree Collapse file tree 5 files changed +46
-0
lines changed Expand file tree Collapse file tree 5 files changed +46
-0
lines changed Original file line number Diff line number Diff line change @@ -31,3 +31,4 @@ was used to develop it.
3131 structures.
32321 . ` code-organization ` : illustration of how to organize code in packages
3333 and modules.
34+ 1 . ` error-handling ` : simple illustration of error handling.
Original file line number Diff line number Diff line change 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.
Original file line number Diff line number Diff line change 1+ 3.7
2+ 3.3
Original file line number Diff line number Diff line change 1+ 3.7
2+ 5.1
3+ some_string
4+ 5.2
Original file line number Diff line number Diff line change 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 )
You can’t perform that action at this time.
0 commit comments