UnboundLocalError问题
#!/bin/python def fn(): try: a=0 b = open("1.py") raise "11" #这个异常不是必然发生,我这里只是假设 c = open("2.py") except: if b: b.close() if c: c.close() if __name__ == "__main__": fn()
def fn(): try: a = 0 b, c = False, False b = open('1.py') c = open('2.py') except: if b: b.close() if c: c.close()if __name__ == "__main__": fn()
[解决办法]
def fn(): a = b = False try: a=0 b = open("1.py") raise "11" #这个异常不是必然发生,我这里只是假设 c = open("2.py") except: if b: b.close() if c: c.close()if __name__ == "__main__": fn()
[解决办法]
你可以嵌套使用try...except...类似:
def fn(): try: a=0 b = open("1.py") raise "11" #这个异常不是必然发生,我这里只是假设 c = open("2.py") except: try: b.close() c.close() except: passif __name__ == "__main__": fn()