B074JG8W8Z EBOK by Powerful Python 2nd Edition
Author:Powerful Python, 2nd Edition
Language: eng
Format: azw3, epub
Publisher: Powerful Python Press
Published: 0101-01-01T00:00:00+00:00
Exceptions Are Objects
An exception is an object: an instance of an exception class. KeyError, IndexError, TypeError and ValueError are all built-in classes, which inherit from a base class called Exception. Writing code like except KeyError: means "if the exception just raised is of type KeyError, run this block of code."
So far, we havenât dealt with those exception objects directly. And often, you donât need to. But sometimes you want more information about what happened, and capturing the exception object can help. Hereâs the structure:
try: do_something() except ExceptionClass as exception_object: handle_exception(exception_object)
where ExceptionClass is some exception class, like KeyError, etc. In the except block, exception_object will be an instance of that class. You can choose any name for that variable; no one actually calls it exception_object, preferring shorter names like ex, exc, or err. The methods and contents of that object will depend on the kind of exception, but almost all will have an attribute called args. That will be a tuple of what was passed to the exceptionâs constructor. The args of a KeyError, for example, will have one element - the missing key:
# Atomic numbers of noble gasses. nobles = {'He': 2, 'Ne': 10, 'Ar': 18, 'Kr': 36, 'Xe': 54} def show_element_info(elements): for element in elements: print('Atomic number of {} is {}'.format( element, nobles[element])) try: show_element_info(['Ne', 'Ar', 'Br']) except KeyError as err: missing_element = err.args[0] print('Missing data for element: ' + missing_element)
Running this code gives you the following output:
Atomic number of Ne is 10 Atomic number of Ar is 18 Missing data for element: Br
The interesting bit is in the except block. Writing except KeyError as err stores the exception object in the err variable. That lets us look up the offending key, by peeking in err.args. Notice we could not get the offending key any other way, unless we want to modify show_element_info (which we may not want to do, or perhaps canât do, as described before).
Letâs walk through a more sophisticated example. In the os module, the makedirs function will create a directory:
# Creates the directory "riddles", relative # to the current directory. import os os.makedirs("riddles")
By default, if the directory already exists, makedirs will raise FileExistsError:[3] Imagine you are writing a web application, and need to create an upload directory for each new user. That directory should not exist; if it does, thatâs an error and needs to be logged. Our upload-directory-creating function might look like this:
# First version.... import os import logging UPLOAD_ROOT = "/var/www/uploads/" def create_upload_dir(username): userdir = os.path.join(UPLOAD_ROOT, username) try: os.makedirs(userdir) except FileExistsError: logging.error( "Upload dir for new user already exists")
Itâs great we are detecting and logging the error, but the error message isnât informative enough to be helpful. We at least need to know the offending username, but itâs even better to know the directoryâs full path (so you donât have to dig in the code to remind yourself what UPLOAD_ROOT was set to).
Fortunately, FileExistsError objects have an attribute called filename. This is a string, and the path to the already-existing directory. We can
Download
B074JG8W8Z EBOK by Powerful Python 2nd Edition.epub
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
What's Done in Darkness by Kayla Perrin(26574)
The Fifty Shades Trilogy & Grey by E L James(19059)
Shot Through the Heart: DI Grace Fisher 2 by Isabelle Grey(19039)
Shot Through the Heart by Mercy Celeste(18916)
Wolf & Parchment: New Theory Spice & Wolf, Vol. 10 by Isuna Hasekura and Jyuu Ayakura(17099)
Python GUI Applications using PyQt5 : The hands-on guide to build apps with Python by Verdugo Leire(16949)
Peren F. Statistics for Business and Economics...Essential Formulas 3ed 2025 by Unknown(16850)
Wolf & Parchment: New Theory Spice & Wolf, Vol. 03 by Isuna Hasekura and Jyuu Ayakura & Jyuu Ayakura(16807)
Wolf & Parchment: New Theory Spice & Wolf, Vol. 01 by Isuna Hasekura and Jyuu Ayakura & Jyuu Ayakura(16431)
The Subtle Art of Not Giving a F*ck by Mark Manson(14332)
The 3rd Cycle of the Betrayed Series Collection: Extremely Controversial Historical Thrillers (Betrayed Series Boxed set) by McCray Carolyn(14113)
Stepbrother Stories 2 - 21 Taboo Story Collection (Brother Sister Stepbrother Stepsister Taboo Pseudo Incest Family Virgin Creampie Pregnant Forced Pregnancy Breeding) by Roxi Harding(13591)
Scorched Earth by Nick Kyme(12750)
Drei Generationen auf dem Jakobsweg by Stein Pia(10951)
Suna by Ziefle Pia(10877)
Scythe by Neal Shusterman(10317)
International Relations from the Global South; Worlds of Difference; First Edition by Arlene B. Tickner & Karen Smith(9507)
Successful Proposal Strategies for Small Businesses: Using Knowledge Management ot Win Govenment, Private Sector, and International Contracts 3rd Edition by Robert Frey(9352)
This is Going to Hurt by Adam Kay(9149)
