How can I use try-except to deal with an error?

Thank you :)

For example, you are trying to open a file that does not exist.

This code will give you a Traceback IOError and the program exits ...

fname = "xyz.txt"
fin = open(fname, "r")

"""my output (if xyz.txt does not exist) -->
Traceback (most recent call last):
  File "error_fname1.py", line 2, in <module>
    fin = open(fname, "r")
IOError: [Errno 2] No such file or directory: 'xyz.txt'
"""

You can trap the error and do something else that would avoid the program exit, if you want to ...

fname = "xyz.txt"
try:
    fin = open(fname, "r")
except:
    print( "Cannot find file %s" % fname )
    # do something else here

"""my output (if xyz.txt does not exist) -->
Cannot find file xyz.txt
"""

You can be more specific and include the type of error ...

fname = "xyz.txt"
try:
    fin = open(fname, "r")
except IOError:
    print( "Cannot find file %s" % fname )
    # do something else here

"""my output (if xyz.txt does not exist) -->
Cannot find file xyz.txt
"""

Even more specific with type of error and error message ...

fname = "xyz.txt"
try:
    fin = open(fname, "r")
# Python2
#except IOError, which_error:
# Python3
except IOError as which_error:
    print( "Unable to open file: %s" % which_error )
    # do something else here

"""my output (if xyz.txt does not exist) -->
Unable to open file: [Errno 2] No such file or directory: 'xyz.txt'
"""

Thank you so much!It helps a lot

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.