So let’s say i have this python code:
def loopForEachFileInDirectory(self, conn):
for filename in os.listdir(uploadedFilesDirectory):
try:
self.insertNewEntryForStagingFile(conn, filename)
self.copyFilesToStagingDirectory(filename)
except: ???
def copyFilesToStagingDirectory(self, filename):
logging.info("copying %s to youtube_ready",filename)
try:
shutil.copy(uploadedFilesDirectory+filename, stagingDirectory)
logging.info("move successful")
except shutil.Error,e:
logging.warn("move failed for reasons \n\t%d:%s", e.args[0],e.args[1])
raise ???
Now, the “loopForEachFileInDirectory” method is going to have a few more methods in it – i’m doing a bit of clean coding (cheers Robert Martin) here. What i’d like is to bubble up any exceptions from the sub-methods, and if anything happens in the main loop, bail on that loop and continue.
The question is, what is the rule for bubbling up a generic exception? Do i just raise on its own? And if so, how do i generically throw an exception, and how do i catch and log the details of a generic exception?
Yes. The short answer is to just use
raise.The above answer the other submitter posted is correct, but it doesn’t provide much in the way of context.
Exceptionis the base class exception.except Exceptionworks across all types ofExceptionbecause all Python exceptions inherit from this class.exceptstatements can specify an argument which points to the the exception object.I don’t believe that specifying it is strictly necessary in this context. In fact, it’s likely sufficient to bubble up an exception with the default:
without any real need to specify an exception type or the variable
ereferencing the particular exception object.logging.exceptionis a good way to go. Try it like so: