zoukankan      html  css  js  c++  java
  • Python

    From:http://interactivepython.org/courselib/static/pythonds/Introduction/ExceptionHandling.html

    Exception Handling

    There are two types of errors that typically occur when writing programs.

    • syntax error - simply means that the programmer has made a mistake in the structure of a statement or expression.

    For example:

    >>> for i in range(10)
    SyntaxError: invalid syntax (<pyshell#61>, line 1)
    • logic error - , denotes a situation where the program executes but gives the wrong result.

    In some cases, logic errors lead to very bad situations such as trying to divide by zero or trying to access an item in a list where the index of the item is outside the bounds of the list. In this case, the logic error leads to a runtime error that causes the program to terminate. These types of runtime errors are typically called exceptions.

    >>> anumber = int(input("Please enter an integer "))
    Please enter an integer -23
    >>> print(math.sqrt(anumber))
    Traceback (most recent call last):
      File "<pyshell#102>", line 1, in <module>
        print(math.sqrt(anumber))
    ValueError: math domain error
    >>>

      •   We can handle this exception by calling the print function from within a try block. 
    >>> try:
           print(math.sqrt(anumber))
        except:
           print("Bad Value for square root")
           print("Using absolute value instead")
           print(math.sqrt(abs(anumber)))
    
    Bad Value for square root
    Using absolute value instead
    4.79583152331
    >>>
      •   It is also possible for a programmer to cause a runtime exception by using the raise statement. For example, instead of calling the square root function with a negative number, we could have checked the value first and then raised our own exception. The code fragment below shows the result of creating a new RuntimeError exception. Note that the program would still terminate but now the exception that caused the termination is something explicitly created by the programmer.
    >>> if anumber < 0:
    ...    raise RuntimeError("You can't use a negative number")
    ... else:
    ...    print(math.sqrt(anumber))
    ...
    Traceback (most recent call last):
      File "<stdin>", line 2, in <module>
    RuntimeError: You can't use a negative number
    >>>


    There are many kinds of exceptions that can be raised in addition to the RuntimeError shown above. See the Python reference manual for a list of all the available exception types and for how to create your own.
     
  • 相关阅读:
    用于展现图表的50种JavaScript库
    EditPlus常用正则表达式
    人工智能生成仿真人脸
    树莓派搭建SVN服务器
    JS三座大山再学习 ---- 异步和单线程
    JS三座大山再学习 ---- 作用域和闭包
    基于C#的MongoDB数据库开发应用(2)--MongoDB数据库的C#开发
    基于C#的MongoDB数据库开发应用(1)--MongoDB数据库的基础知识和使用
    大数据高效复制的处理案例分析总结
    基于DevExpress的Winform程序安装包的制作
  • 原文地址:https://www.cnblogs.com/keepSmile/p/7880232.html
Copyright © 2011-2022 走看看