"try" Statement to Catch Execution

This section provides a quick introduction of 'try' statement, which allows you to manage exceptions raised from a block of sub-statements.

What Is "try" Statement? A "try" statement is a compound statement that allows you to manage exceptions raised from a block of sub-statements.

A "try" statements must have a "try" clause followed by multiple optional "except" clauses, an optional "else" clause, and an optional "finally" clause:

try:
  sub-statement
  sub-statement
  ...
except [exception_type [as variable_name]]:
  sub-statement
  sub-statement
  ...
...
else:
  sub-statement
  sub-statement
  ...
finally:
  sub-statement
  sub-statement
  ...

The execution of a "try" statement follows the following logics:

Here is a Python sample code, try_test.py, that shows you how to use "try" statements.

#  try_test.py
#- Copyright 2011 (c) HerongYang.com. All Rights Reserved.
#
import sys, os

data = b''
try:
   file = sys.argv[1]
   fd = os.open(file, os.O_RDONLY)
   data = os.read(fd, 80)
   os.close(fd)
except OSError as e:
   print("Catch the OSError: "+str(e))
except IndexError as e:
   print("Catch the IndexError: "+str(e))
except:
   print("Catch all other errors here.")
else:
   print("No exception caught :-)")
finally:
   print("Test is done")

print("Data = "+data.decode())

If you run this sample code, you should get:

herong$ python try_test.py
  Catch the IndexError: list index out of range
  Test is done
  Data =

herong$ python try_test.py junk
  Catch the OSError: [Errno 2] No such file or directory: 'junk'
  Test is done
  Data =

herong$ python try_test.py sample.txt
  No exception caught :-)
  Test is done
  Data = some text

As you can see from the output, the sample code works as expected.

Note that the last "except" clause does not include the "exception_type as variable_name" part. It will catch all remaining exceptions, since will match any exception type.

However, using an "except" clause without "exception_type" will not give any access to the exception object. So it's better to provide the exception base type "Exception", which will also match any exception type. See the syntax below:

try:
...
except Exception as e:
   print("Catch all other errors here.")
   print(e)
...

Table of Contents

 About This Book

 Running Python Code Online

 Python on macOS Computers

 Python on Linux Computers

 Built-in Data Types

 Variables, Operations and Expressions

Statements - Execution Units

 What Is Statement

 "pass" Statement - Do Nothing Statement

 Expression Statement - One Expression Only

 "=" Statement - Assignment Statement

 "del" Statement - Delete Statement

 "import" Statement to Load Modules

 "if" Statement for Conditional Execution

 "while" Statement for Execution Loop

 "for" Statement for Iterative Execution

"try" Statement to Catch Execution

 "with" Statement for Context Manager

 "match" Statement for Pattern Match

 Function Statement and Function Call

 Iterators, Generators and List Comprehensions

 Classes and Instances

 Modules and Module Files

 Packages and Package Directories

 "sys" and "os" Modules

 "pathlib" - Object-Oriented Filesystem Paths

 "pip" - Package Installer for Python

 SciPy.org - Python Libraries for Science

 pandas - Data Analysis and Manipulation

 Anaconda - Python Environment Manager

 Jupyter Notebook and JupyterLab

 References

 Full Version in PDF/EPUB