python-novice-gapminder icon indicating copy to clipboard operation
python-novice-gapminder copied to clipboard

Additional content for chapter 13: Try and Except

Open jchaptinel opened this issue 7 years ago • 1 comments

Hi,

I think that a quick introduction to Try and Except to manage exception may be necessary, especially for scripts that takes multiple hours to run. I think it can be done in 20 minutes. Besides, it is built upon the content of chapter 13.

Here is the content I suggest:

Try and Except

  • Try and Except are two functions working together.
  • If and exception occurs in Try, the code in Except is executed instead
  • The code after the block Try and Except is executed normally
try:
    #your code

except ExceptionName:
    #if an exception with the name ExceptionName occurs in try, execute the code in except

#continue to execute the following code

Example

try: 
   print(a)

except NameValue:
   print('This variable does not exist')

print('The execution still goes on despite the exception')
  • Depending on the exception in try, different actions can be taken
  • Typical exception names are ValueError, IOError, NameError, SyntaxError, etc.
try: 
	#your code
except ExceptionName1:
	#if Exception1 occurs in try, execute this code 
	
except ExceptionName2:
	#if Exception2 occurs in try, execute this code 
	
#continue to execute the following code

hands-on

How can you use Try and Except to display the content of a list of file that contains a missing file right in the middle ?

tampered_filelist = glob.glob('data/*.csv')
tampered_filelist[2] = 'data/nonExistingFile.csv'

for filename in tampered_filelist:
    print('\nDisplay content of', filename )
    print(pandas.read_csv(filename))
    
print('\nAll the files that coudl be loaded are displayed')

Solution:

tampered_filelist = glob.glob('data/*.csv')
tampered_filelist[2] = 'data/nonExistingFile.csv'

for filename in tampered_filelist:
    try: 
        print ('\nDisplay content of', filename )
        print(pandas.read_csv(filename))

    except FileNotFoundError:
        print('\n\nThe file ', filename, ' could not be loaded, the file is skipped')
        continue

print('\nAll the files that could be loaded are displayed')

jchaptinel avatar Nov 28 '18 15:11 jchaptinel

Thanks for your suggestion! I believe we first need a discussion on if new material taking 20 minutes can be fit into the schedule, without taking out something else. I leave the question open for the other maintainers.

vahtras avatar Nov 28 '18 16:11 vahtras