Blog Archive

Wednesday, April 19, 2023

[Tutorial & Examples] try block in Python

1) Motivation:

Why we need it?


open('demo_read.txt')

If the 'demo_read.txt' is not exist yet,  we will encounter 2 issues:

a) The script will exit immediately 

b) The script will print a bit verbose and messy error message:


Traceback (most recent call last):

  File "c:\Users\liuga\git_downloads\study\python\pickle_notes.py", line 1, in <module>

    open('demo_read.txt')

FileNotFoundError: [Errno 2] No such file or directory: 'demo_read.txt'


Can we continue run the script without exiting? 

Can we print out a clean or better customized error messages?

Yes, yes, Let's move on.

2) Better way!

try:
    open('demo_read.txt')
except FileNotFoundError as e:
    print(e)

The terminal will display:

[Errno 2] No such file or directory: 'demo_read.txt'


3) What is more?

Example 1:

try:
    open('demo_read.txt')
    x = 0
except FileNotFoundError as e:
    print(e)
except Exception as e:
    print(e)
else:
    print(f'Everthing is fine, no error!')
finally:
    print(f'The try-block is done no matter what happens. You will always see this line')

When running it, terminal will display:

Everthing is fine, no error!

The try-block is done no matter what happens. You will always see this line


Example 2:

try:
    open('demo_read.txt')
    x = y
except FileNotFoundError as e:
    print(e)
except Exception as e:
    print(e)
else:
    print(f'Everthing is fine, no error!')
finally:
    print(f'The try-block is done no matter what happens. You will always see this line')

When running it, terminal will display:

name 'y' is not defined

The try-block is done no matter what happens. You will always see this line


Example 3:


files = ['demo_read0.txt', 'demo_read.txt']
for file in files:    
    print(f'processing {file}')
    try:        
        f = open(file)                
    except FileNotFoundError as e:
        print(e)
    except Exception as e:
        print(e)
    else:
        print(f'Everthing is fine, no error for {file}')
        f.close()
    finally:
        print(f'The try-block is done no matter what happens. You will always see this line')


When running it, terminal will display:

processing demo_read0.txt

[Errno 2] No such file or directory: 'demo_read0.txt'

The try-block is done no matter what happens. You will always see this line

processing demo_read.txt

Everthing is fine, no error for demo_read.txt

The try-block is done no matter what happens. You will always see this line 


Conclusion:

Now I would like to sum up the try-block with my own language as this: it is a mechanism to handle error with more choices. 


This article is inspired by [1]


Reference:

[1] https://www.youtube.com/watch?v=NIWwJbo-9_8