• Facing Errors In Python- Part 4

    Working with exception arguments

    Most exceptions don’t provide arguments (a list of values that you can check for additional information). The exception either occurs or it doesn’t. However, a few exceptions do provide arguments, and you see them used later in the book. The arguments tell you more about the exception and provide details that you need to correct it.

    For the sake of completeness, this Post includes a simple example that generates an exception with an argument. You can safely skip the remainder of this section if desired because the information is covered in more detail later in the book.

     Open a Python File window.

    You see an editor in which you can type the example code.

     Type the following code into the window — pressing Enter after each line:

    import sys

    try:

    File = open('myfile.txt') except IOError as e:
    print("Error opening file!\r\n" +
    "Error Number: {0}\r\n".format(e.errno) + "Error Text: {0}".format(e.strerror))
    else:
    print("File opened as expected.") File.close();

    This example uses some advanced features. The import statement obtains code from another file. Post 10 tells you how to use this Python feature.

    The open() function opens a file and provides access to the file through the File variable. Post 15 tells you how file access works. Given that myfile.txt doesn’t exist in the application directory, the operating system can’t open it and will tell Python that the file doesn’t exist.

    Trying to open a nonexistent file generates an IOError exception. This particular exception provides access to two arguments:

     errno: Provides the operating system error number as an integer

     strerror: Contains the error information as a human-readable string

    The as clause places the exception information into a variable, e, that you can access as needed for additional information. The except block contains a print() call that formats the error information into an easily read error message.

    If you should decide to create the myfile.txt file, the else clause executes. In this case, you see a message stating that the file opened normally. The code then closes the file without doing anything with it.

     Choose RunRun Module.

    You see a Python Shell window open. The application displays the Error opening file information, as


    Obtaining a list of exception arguments

    The list of arguments supplied with exceptions varies by exception and by what the sender pro­ vides. It isn’t always easy to figure out what you can hope to obtain in the way of additional informa­ tion. One way to handle the problem is to simply print everything using code like this

    import sys

    try:

    File = open('myfile.txt') except IOError as e:

    for Arg in e.args: print(Arg)
    else:
    print("File opened as expected.") File.close();

    The args property always contains a list of the exception arguments in string format. You can use a simple for loop to print each of the arguments. The only problem with this approach is that you’re missing the argument names, so you know the output information (which is obvious in this case), but you don’t know what to call it.

    A more complex method of dealing with the issue is to print both the names and the contents of the arguments. The following code displays both the names and the values of each of the arguments

    import sys

    try:
    File = open('myfile.txt')

    except IOError as e: for Entry in dir(e):

    if (not Entry.startswith("_")): try:

    print(Entry, " = ", e.__getattribute__(Entry)) except AttributeError:
    print("Attribute ", Entry, " not accessible.")
    else:
    print("File opened as expected.") File.close();

    In this case, you begin by getting a listing of the attributes associated with the error argument object using the dir() function. The output of the dir() function is a list of strings containing the names of the attributes that you can print. Only those arguments that don’t start with an under­ score (_) contain useful information about the exception. However, even some of those entries are inaccessible, so you must encase the output code in a second try...except block

    The attribute name is easy because it’s contained in Entry. To obtain the value associated with that attribute, you must use the __getattribute__() function and supply the name of the attribute you want. When you run this code, you see both the name and the value of each of the attributes supplied with a particular error argument object. In this case, the actual output is as follows:

    args = (2, 'No such file or directory')
    Attribute  characters_written  not accessible.
    errno = 2
    filename = myfile.txt
    strerror =  No such file or directory
    winerror = None
    with_traceback  =  <built-in method with_traceback of
    FileNotFoundError object at 0x0000000003416DC8>
       

    Handling multiple exceptions with a single except clause


    Most applications can generate multiple exceptions for a single line of code. How you handle the multiple exceptions depends on your goals for the application, the types of exceptions, and the relative skill of your users. Sometimes when working with a less skilled user, it’s simply easier to say that the application experienced a nonrecoverable error and then log the details into a log file in the application directory or a central location.

    Using a single except clause to handle multiple exceptions works only when a common source of action fulfills the needs of all the exception types. Otherwise, you need to handle each exception individually. The following steps show how to handle multiple exceptions using a single except clause.

     Open a Python File window.

    You see an editor in which you can type the example code.

     Type the following code into the window — pressing Enter after each line:

    try:

    Value = int(input("Type a number between 1 and 10: "))
    except (ValueError, KeyboardInterrupt):
    print("You must type a number between 1 and 10!") else:

    if (Value > 0) and (Value <= 10): print("You typed: ", Value)
    else:
    print("The value you typed is incorrect!")

    However, notice that the except clause now sports both a ValueError and a KeyboardInterrupt exception. In addition, these exceptions appear within parentheses and are separated by commas.

     Choose RunRun Module.

    You see a Python Shell window open. The application asks you to type a number between 1 and 10.

     Type Hello and press Enter.

    The application displays an error message.

     Perform Steps 3 and 4 again, but type 22 instead of Hello.

    The application outputs the expected range error message.

     Perform Steps 3 and 4 again, but press Ctrl+C, Cmd+C, or the alterna-tive for your platform instead of typing anything.

    You see the error message that’s usually associated with error input.

     Perform Steps 3 and 4 again, but type 7 instead of Hello.

    This time, the application finally reports that you’ve provided a correct value of 7.

    Handling multiple exceptions with multiple except clauses

    When working with multiple exceptions, it’s usually a good idea to place each exception in its own except clause. This approach allows you to provide custom handling for each exception and makes it easier for the user to know precisely what went wrong. Of course, this approach is also a lot more work.

    The following steps demonstrate how to perform exception handling using multiple except clauses.

    Open a Python File window.

    You see an editor in which you can type the example code.

     Type the following code into the window — pressing Enter after each line:

    try:

    Value = int(input("Type a number between 1 and 10: "))
    except ValueError:
    print("You must type a number between 1 and 10!") except KeyboardInterrupt:
    print("You pressed Ctrl+C!") else:

    if (Value > 0) and (Value <= 10): print("You typed: ", Value)
    else:
    print("The value you typed is incorrect!")

    Notice the use of multiple except clauses in this case. Each except clause handles a different exception. You can use a combination of techniques, with some except clauses handling just one exception and other except clauses handling multiple exceptions. Python lets you use the approach that works best for the error-handling situation.

     Choose RunRun Module.

    You see a Python Shell window open. The application asks you to type a number between 1 and 10.

     Type Hello and press Enter.

    The application displays an error message.

     Perform Steps 3 and 4 again, but type 22 instead of Hello.

    The application outputs the expected range error message.

     Perform Steps 3 and 4 again, but press Ctrl+C, Cmd+C, or the alterna-tive for your platform instead of typing anything.

    The application outputs a specific message that tells the user what went wrong,

     Perform Steps 3 and 4 again, but type 7 instead of Hello.

    This time, the application finally reports that you’ve provided a correct value of 7.



  • 0 comments:

    Post a Comment

    Powered by Blogger.

    Tags

    Popular Posts