Adding Python exception handling structures (try/except/else)

Python has built-in exception handling structures that allows you to capture error messages that are generated. Using this error information, you can then display a more appropriate message to the end user and respond to the situation as needed.

Getting ready

Exceptions are unusual or error conditions that occur in your code. Exception statements in Python enable you to trap and handle errors in your code, allowing you to gracefully recover from error conditions. In addition to error handling, exceptions can be used for a variety of other things, including event notification and handling of special cases.

Python exceptions occur in two ways. Exceptions in Python can either be intercepted or triggered. When an error condition occurs in your code, Python automatically triggers an exception, which may or may not be handled by your code. It is up to you as a programmer to catch an automatically triggered exception. Exceptions can also be triggered manually by your code. In this case, you would also provide an exception handling routine to catch these manually triggered exceptions. You can manually trigger an exception by using the raise statement.

The try/except statement is a complete, compound Python statement, which is used to handle exceptions. This variety of try statement starts with a try header line followed by a block of indented statements, then one or more optional except clauses that name exceptions to be caught, and an optional else clause at the end.

The try/except/else statement works as follows. Once inside a try statement, Python marks the fact that you are in a try block and knows that any exception condition that occurs within this block will be forwarded to the various except statements for handling.

Each statement inside the try block is executed. Assuming there aren't any conditions in which exceptions occur, the code pointer will then jump to the else statement and execute the code block contained within the else statement before moving to the next line of code below the try block. If an exception occurs inside the try block, Python searches for a matching exception code. If a matching exception is found, the code block inside the except block is executed. The code then reappears below the full try statement. The else statements are not executed in this case. If a matching exception header is not found, Python will propagate the exception to a try statement above this code block. In the event that no matching except header is found, the exception comes out of the top level of the process. This results in an unhandled exception and you wind up with the type of error message that we saw in our first recipe in this chapter. This is illustrated in the following figure:

Getting ready

In this recipe, we're going to add in some basic Python exception handling structures. There are several variations of the try/except/else/finally exception handling structure. In this recipe, we'll start with a very simple try/except structure.

How to do it…

Follow these steps to add Python error handling structures to a script.

  1. If necessary, open the C:ArcpyBookCh11ErrorHandling.py file in IDLE.
  2. Alter your script to include a try/except block:
    import arcpy
    try:
      arcpy.env.workspace = "c:/ArcpyBook/data"
      arcpy.Buffer_analysis("Streams.shp","Streams_Buff.shp")
    except:
      print("Error")
  3. You can check your work by examining the C:ArcpyBookcodeCh11ErrorHandling2.py solution file.
  4. Save and run the script. You should see the simple Error message. This is no more helpful than the output we received in our first recipe. In fact, it's even less useful. However, the point of this recipe is simply to introduce you to the try/except error handling structure.

How it works…

This is an extremely simple structure. The try block indicates that everything indented under the try statement will be subject to exception handling. If an exception of any type is found, control of the code processing jumps to the except section and prints the error message(s), which in this case is simply Error. Now, as I mentioned, this is hardly informative to your users, but hopefully, it gives you a basic idea of how the try/except blocks work, and as a programmer you will better understand any errors reported by your users. In the next recipe, you'll learn how to add tool-generated messages to this structure.

There's more…

The other type of try statement is the try/finally statement, which allows for finalization actions. When a finally clause is used in a try statement, its block of statements always run at the very end, whether an error condition occurs or not. This is how the try/finally statement works: if an exception occurs, Python runs the except block, then the finally block. If an exception does not occur during execution, Python runs the try block, and then the finally block. This is useful when you want to make sure that an action takes place after a code block runs, regardless of whether or not an error condition occurs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset