import errno
try:shutil.rmtree(path)except OSError as e:if e.errno != errno.ENOENT:# ignore "No such file or directory", but re-raise other errorsraise
try:#Your code in which exception can occurexcept <here we can put in a particular exception name>:# We can call that exception here also, like ZeroDivisionError()# now your code# We can put in a finally block alsofinally:# Your code...
import errno
try:shutil.rmtree(path)except OSError as error:if error.errno == errno.ENOENT: # no such file or directorypasselse: # we had an OSError we didn't expect, so reraise itraise
class MyExceptionHandler:
def __enter__(self):... # Do whatever when "with" block is startedreturn self
def __exit__(self, exc_type, exc_value, tb):return True
然后是实际代码:
with MyExceptionHandler():... # Code that may or may not raise an exceptionshutil.rmtree(path)