If I run the following Python script and believe that my file will be read, the IOError handler will pick up a custom exception, Not sure how I manage the custom exceptions to be raised? Can anyone help please?
class custom IOError: def __init __ (self, msg): super (customOur, self) .__ init __ () self.error_msg = msg Try: # Open file F: Read with open (filename) as: print line, excluding IOError: Extend CustomIOError ('Exception Message') # Except customIOError: # sys.exit (0) Its Besides, if Python supports polymorphism, then why can not I directly remove the exception of the base class directly, with the exception handler of the derived class?
Try: CustomIOError: pass This will not work, a part of the stack trace will end the program execution after printing.
An exception is caught once except the section , the same Any subsequent excepts in the block are ignored, so you can not do this:
try: ... except something: MyError: MyError: You should try another block around the whole thing:
Try: Try: ... except something else: Extend MyError except MyError: & lt; - For the second question, it works another time: Try: Increase CustomIOError except for IOError: & Lt; - Work pass
This is because CustomIOError is a IOError , but IOError is not CustomIOError (Compare: The dog is an animal, but (none) is a beast dog), so except you do not match it.
In general, custom exceptions provide a way to wrap common errors in application-specific people, so that the high-level code is not wrong to deal with some error details. For example, you have a function that reads a file and writes content in a SQL database code that invents this function only wants to know if it is successful or unsuccessful, the details are irrelevant (though later Should be logged to check in). Therefore, the function throws an exception only to indicate that it has failed:
# High-level code class UserInterface: def writeButtonClick: try: readAndWrite () ReadAndWriteFailure: showMessage ( "Problem! Again") # Lower-level code class ReadAndWriteFailure: Def def readAndWrite (): Try: fp = open (someFile) db = sql.connection () in fp: db.execute (line) to IOError Except: the log extends ReadAndWriteFailure (excluding this SQLError): Increase it ReadAndWriteFailure () etc. Login
No comments:
Post a Comment