python——day_08:错误和异常

古城微笑少年丶 2023-06-11 14:24 147阅读 0赞

title: ‘python——day_08:错误和异常’
date: 2019-10-30 22:07:28
categories:

  • python基础
    tags:
  • python基础

‘python——day_08:错误和异常’

错误

  • 语法错误或者是解析错误

异常

  • 运行期检测到的错误被称为异常
  • 大多数的异常都不会被程序处理,都以错误信息的形式展现在命令行
  • 示例:

    1. >>>10 * (1/0)
    2. Traceback ​(most recent call last):
    3. File "<stdin>", line 1, in ?
    4. ZeroDivisionError: division by zero
    5. >>> 4 + spam*3
    6. Traceback ​(most recent call last):
    7. File "<stdin>", line 1, in ?
    8. NameError: name 'spam' is not defined
    9. >>> '2' + 2
    10. Traceback ​(most recent call last): File "<stdin>", line 1, in ?
    11. TypeError: Can't convert 'int' object to str implicitly
  • 示例2:

    1. try:
    2. x = int(input("Please enter a number: "))
    3. break
    4. except ValueError:
    5. print("Oops! That was no valid number. Try again ")
    1. 首先,执行try子句(在关键字try和关键字except之间的语句)
    2. 如果没有异常发生,忽略except子句,try子句执行后结束。
    3. 如果在执行try子句的过程中发生了异常,那么try子句余下的部分将被忽略。如果异常的类型和 except 之后的名称相符,那么对应的except子句将被执行。最后执行 try 语句之后的代码。
    4. 如果一个异常没有与任何的except匹配,那么这个异常将会传递给上层的try中
  • 一个 try 语句可能包含多个except子句,分别来处理不同的特定的异常。最多只有一个分支会被执行。

    处理程序将只针对对应的try子句中的异常进行处理,而不是其他的 try 的处理程序中的异常。

    一个except子句可以同时处理多个异常,这些异常将被放在一个括号里成为一个元组

    1. except (RuntimeError, TypeError, NameError):
    2. pass
  • try except 语句还有一个可选的else子句,如果使用这个子句,那么必须放在所有的except子句之后。这个子句将在try子句没有发生任何异常的时候执行使用 else 子句比把所有的语句都放在 try 子句里面要好,这样可以避免一些意想不到的、而except又没有捕获的异常
  • 异常处理并不仅仅处理那些直接发生在try子句中的异常,而且还能处理子句中调用的函数(甚至间接调用的函数)里抛出的异常

    1. >>>def this_fails():
    2. x = 1/0
    3. >>> try:
    4. this_fails()
    5. except ZeroDivisionError as err:
    6. print('Handling run-time error:', err)
    7. Handling run-time error: int division or modulo by zero
  • raise 唯一的一个参数指定了要被抛出的异常。它必须是一个异常的实例或者是异常的类(也就是 Exception 的子类)如果你只想知道这是否抛出了一个异常,并不想去处理它,那么一个简单的 raise 语句就可以再次把它抛出

    1. >>>try:
    2. raise NameError('HiThere')
    3. except NameError:
    4. print('An exception flew by!')
    5. raise
    6. An exception flew by!
    7. Traceback (most recent call last):
    8. File "<stdin>", line 2, in ?
    9. NameError: HiThere
  • 用户自定义异常

    1. >>>class MyError(Exception):
    2. def __init__(self, value):
    3. self.value = value
    4. def __str__(self):
    5. return repr(self.value)

    当创建一个模块有可能抛出多种不同的异常时,一种通常的做法是为这个包建立一个基础异常类,然后基于这个基础类为不同的错误情况创建不同的子类

    1. class Error(Exception):
    2. """Base class for exceptions in this module."""
    3. pass
    4. class InputError(Error):
    5. """Exception raised for errors in the input. Attributes: expression -- input expression in which the error occurred message -- explanation of the error """
    6. def __init__(self, expression, message):
    7. self.expression = expression
    8. self.message = message
    9. class TransitionError(Error):
    10. """Raised when an operation attempts a state transition that's not allowed. Attributes: previous -- state at beginning of transition next -- attempted new state message -- explanation of why the specific transition is not allowed """
    11. def __init__(self, previous, next, message):
    12. self.previous = previous
    13. self.next = next
    14. self.message = message
  • 定时清理行为:不管 try 子句里面有没有发生异常,finally 子句都会执行。

    如果一个异常在 try 子句里(或者在 except 和 else 子句里)被抛出,而又没有任何的 except 把它截住,那么这个异常会在 finally 子句执行后被抛出

    1. >>>def divide(x, y):
    2. try:
    3. result = x / y
    4. except ZeroDivisionError:
    5. print("division by zero!")
    6. else:
    7. print("result is", result)
    8. finally:
    9. print("executing finally clause")
    10. >>> divide(2, 1)
    11. result is 2.0
    12. executing finally clause
    13. >>> divide(2, 0)
    14. division by zero!
    15. executing finally clause
    16. >>> divide("2", "1")
    17. executing finally clause
    18. Traceback (most recent call last):
    19. File "<stdin>", line 1, in ?
    20. File "<stdin>", line 3, in divide
    21. TypeError: unsupported operand type(s) for /: 'str' and 'str'

发表评论

表情:
评论列表 (有 0 条评论,147人围观)

还没有评论,来说两句吧...

相关阅读

    相关 08.Java–异常的类型

    08.Java–异常的类型 在实际开发中,经常会在程序编译时期产生一些异常,而这些异常必须要进行处理,这种异常被称为编译时期异常,也称为checked异常。另外还有一种异

    相关 08课:错误异常

    没有完美的程序,就如同没有完美的人,程序执行时有可能出错。一旦出错,严重可导致程序崩溃,造成不可预期的破坏。不过,并不是所有的错误都是致命的,我们并不希望自己的程序因一些非致命