Thus far, you've been working with Python's built-in exceptions, which canhandle most logical or syntactical expressions. However, Python also allowsyou to get creative with exceptions, by generating your own customexceptions if the need arises. This is accomplished via Python's "raise" statement, which is used to raiseerrors which can be detected and resolved by the "try" family of exceptionhandlers. The "raise" statement needs to be passed an exception name, andan optional descriptive string. When the exception is raised, thisexception name and description will be made available to the definedexception handler. Let's go to a quick example - the line of code generates the following error. You can also name and use your own exceptions. In this case, if the username entered at the prompt does not match the namestored in the environment variable $USER, Python will raise a user-definedexception named "someError", with a string of text describing the nature ofthe error. Take a look: Note that the exception must be assigned to an object in order for it towork correctly. Trapping user-defined errors is exactly the same as trapping pre-definedPython errors. The following refinement of the code above illustrates this: Here's the output of the script above, when the wrong username is entered.
blog comments powered by Disqus |