09. Exception(try, raise)

最後更新: 2022-08-05

目錄

 


某看 Exception 的種類

 

>>> import exceptions
>>> dir(exceptions)

 

 


raise (人手引發Exception)

 

raise Exception                           # The root class for all exceptions
raise Exception('hyperdrive overload')    # 格式: raise class(message)

 


try

 

code1:

try:
    ...
# Clean-up Actions (always executed)
finally:
    ...

code2:

try:
    .........
except IOError:
    .........
except TypeError:
    .........
except:
    .........
else:
    ..........

 * "else" keyword to define a block of code to be executed if no errors were raised

    必須要 "except: ... else: ..." 形式

code3:

except (RuntimeError, TypeError, NameError):
    pass

code4:

except IOError as e:
    print "I/O error({0}): {1}".format(e.errno, e.strerror)

code5:

except:
    print "Unexpected error:", sys.exc_info()[0]

 


Error Message

 

try:
    #stuff
except Exception as e:
    print e

 

 

 

Creative Commons license icon Creative Commons license icon