`

Python34-08-异常处理

阅读更多

##异常处理

 

##完整的语法结构如下

##try:

##    ...

##except exception1:

##    ...

##except exception2:

##    ...

##except:

##    ...

##else:

##    ...

##finally:

##    ...

 

##1、实例如下

##print (help(iter))

 

##re = iter(range(5))

##

##try:

##    for i in range(6):

##        print (re.__next__())

##except StopIteration:

##    print ('here is end ',i)

##

##print ('HaHaHaHa')

 

##2、如果try中有异常发生时,将执行异常的归属,执行except

##try:

##    print(a*2)

##except TypeError:

##    print("TypeError")

##except:

##    print("Not Type Error & Error noted")

 

 

##3、无法将异常交给合适的对象,异常将继续向上层抛出

##def test_func():

##    try:

##        m = 1/0

##    except NameError:

##        print("Catch NameError in the sub-function")

##

##try:

##    test_func()

##except ZeroDivisionError:

##    print("Catch error in the main program")

 

##如果try中没有异常,那么except部分将跳过,执行else中的语句。

##finally是无论是否有异常,最后都要做的一些事情。

##

##流程如下,

##try->异常->except->finally

##try->无异常->else->finally

 

 

##抛出异常

print ('Lalala')

raise StopIteration

print ('Hahaha') 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics