def error ()raise hostnameerror("unknown host"def error ()raise timeouterror("timed out"tryerror (except networkerror as eif type(eis hostnameerrorperform special actions for this kind of error in this casethe except networkerror statement catches any exception derived from networkerror to find the specific type of error that was raisedexamine the type of the execution value with type(alternativelythe sys exc_info(function can be used to retrieve information about the last raised exception context managers and the with statement proper management of system resources such as fileslocksand connections is often tricky problem when combined with exceptions for examplea raised exception can cause control flow to bypass statements responsible for releasing critical resources such as lock the with statement allows series of statements to execute inside runtime context that is controlled by an object that serves as context manager here is an examplewith open("debuglog"," "as ff write("debugging\ "statements write("done\ "import threading lock threading lock(with lockcritical section statements end critical section in the first examplethe with statement automatically causes the opened file to be closed when control-flow leaves the block of statements that follows in the second examplethe with statement automatically acquires and releases lock when control enters and leaves the block of statements that follows the with obj statement allows the object obj to manage what happens when control-flow enters and exits the associated block of statements that follows when the with obj statement executesit executes the method obj _enter_ (to signal that new context is being entered when control flow leaves the contextthe method obj _exit_ (type,value,tracebackexecutes if no exception has been raisedthe three arguments to _exit_ (are all set to none otherwisethey contain the typevalueand traceback associated with the exception that has caused control-flow to leave the context the _exit_ (method returns true or false to indicate whether the raised exception was handled or not (if false is returnedany exceptions raised are propagated out of the contextf lib fl ff