zoukankan      html  css  js  c++  java
  • 011: Errors and Exceptions

    1. Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python

    >>> print(a * 3)
    Traceback (most recent call last):
      File "<pyshell#0>", line 1, in <module>
        print(a * 3)
    NameError: name 'a' is not defined

    2. Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal. And example below would be very mindful:

    class MyError(Exception):
        def __init__(self, value):
            self.value = value
        def __str__(self):
            return repr(self.value)
            
    
    def learn_raise_error(num):
        if num == 1:
            result = num / 0
        elif num == 2:
            result = num * a
        elif num == 3:
            result = num + 'learn'
        elif num == 4:
            raise MyError(4)        
        elif num == 5:
            raise Exception('Unkown excetion!')
        else:
            num = 6    
    
    for i in range(1,7,1):
        try:
            learn_raise_error(i)
        except ZeroDivisionError:
            print('ZeroDivisionError')
        except NameError:
            print('NameError')
        except TypeError:
            print('TypeError')
        except MyError:
            print('MyError')        
        except:
            print('Unkown Error')
        # when no exception, then execute else
        else:
            print('No Error')
        # clean up
        finally:
            print('clean up...')

    3. Some objects define standard clean-up actions to be undertaken when the object is no longer needed, regardless of whether or not the operation using the object succeeded or failed.

    with open("myfile.txt") as f:
        for line in f:
            print(line, end="")
  • 相关阅读:
    关于控制地址控件的代码
    获取某个设计项列表界面上查询框中的值的代码
    js中不同值的替换
    js截取字符串方法实例
    抛异常语句的种类及区别
    从获取结果中去除重复记录
    泛微E8升级E9代码修改
    中控考勤数据转换
    WEB打印,分页首行自动带出栏目标题
    VS附加进程调试IIS网站
  • 原文地址:https://www.cnblogs.com/jcsz/p/5117604.html
Copyright © 2011-2022 走看看