Python study notes (54-punch in on time-QQ) 7.24

Task3 exception handling
Exceptions are errors detected during runtime. The computer language defines exception types for possible errors. When a certain error triggers a corresponding exception, the exception handler will be started to restore the normal operation of the program.
1. Summary of Python standard exceptions:
BaseException: the base class of all exceptions
Exception: the base class of regular exceptions
StandardError: the base class of all built-in standard exceptions
ArithmeticError: the base class of all numerical calculation exceptions
FloatingPointError: floating point calculation exception
OverflowError: numeric value The operation exceeds the maximum limit.
ZeroDivisionError: The division is zero.
AssertionError: The assertion statement (assert) failed.
AttributeError: Attempt to access an unknown object attribute.
EOFError: No built-in input, reaching the EOF flag.
EnvironmentError: Base class of operating system exception
IOError: Input/output operation failed
OSError: an exception generated by the operating system (such as opening a non-existent file) WindowsError: system call failed
ImportError: when importing a module failed
KeyboardInterrupt: user interrupted execution
LookupError: invalid data query base class
IndexError: index out of the range of the sequence
KeyError: Find a keyword that does not exist in the dictionary
MemoryError: Memory overflow (the memory can be released by deleting the object) NameError: Attempt to access a non-existent variable
UnboundLocalError: Access to an uninitialized local variable
ReferenceError: Weak reference attempt to access an object that has been garbage collected RuntimeError: General runtime exception
NotImplementedError: Unimplemented method
SyntaxError: Exception caused by syntax error
IndentationError: Exception caused by indentation error
TabError: Tab and space mixed
SystemError: General interpreter system exception
TypeError: Invalid operation between different types
ValueError: Invalid parameter
UnicodeError: Unicode related exception
UnicodeDecodeError: Unicode decoding exception UnicodeEncodeError: exception caused by Unicode encoding error UnicodeTranslateError: exception caused by Unicode conversion error

2. Python standard warning summary
Warning: the base class of warning
DeprecationWarning : warning about deprecated features
FutureWarning: warning about the semantics of the structure will change in the future UserWarning: warning generated by user code PendingDeprecationWarning: warning about the feature will be deprecated RuntimeWarning: warning about suspicious runtime behavior SyntaxWarning: warning about suspicious syntax
ImportWarning: used to trigger a warning during module import UnicodeWarning: warning related to Unicode
BytesWarning: warning related to byte or bytecode
ResourceWarning: warnings related to resource usage

3. Try-except statement

try:
    检测范围
except Exception[as reason]:
    出现异常后的处理代码

The try statement works as follows: First, the try clause (the statement between the keyword try and the keyword except) is executed. If no exception occurs, the except clause is ignored, and the try clause ends after execution. If an exception occurs during the execution of the try clause, the rest of the try clause will be ignored. If the type of the exception matches the name after except, the corresponding except clause will be executed. Finally execute the code after the try statement. If an exception does not match any except, then the exception will be passed to the upper try.
A try statement may contain multiple except clauses to handle different specific exceptions. At most only one branch will be executed. such as:

try:
    int("abc")
    s = 1 + '1'
    f = open('test.txt')
    print(f.read())
    f.close()
except OSError as error:
    print('打开文件出错\n原因是:' + str(error))
except TypeError as error:
    print('类型出错\n原因是:' + str(error))
except ValueError as error:
    print('数值出错\n原因是:' + str(error))

# 数值出错
# 原因是:invalid literal for int() with base 10: 'abc'

Exception handling should adhere to the order of exception specifications, from the most targeted exception to the most general exception.
An except clause can handle multiple exceptions at the same time, and these exceptions will be placed in parentheses as a tuple.

4. Try-except-finally statement

try:
    检测范围
except Exception[as reason]:
    出现异常后的处理代码
finally:
    无论如何都会被执行的代码

Regardless of whether an exception occurs in the try clause, the finally clause will be executed. If an exception is thrown in the try clause, and there is no except to intercept it, then the exception will be thrown after the finally clause is executed.

def divide(x, y):
    try:
        result = x / y
        print("result is", result)
    except ZeroDivisionError:
        print("division by zero!")
    finally:
        print("executing finally clause")


divide(2, 1)
# result is 2.0
# executing finally clause
divide(2, 0)
# division by zero!
# executing finally clause
divide("2", "1")
# executing finally clause
# TypeError: unsupported operand type(s) for /: 'str' and 'str'

5. try-except-else statement

try:
    检测范围
except:
    出现异常后的处理代码
else:
    如果没有异常执行这块代码

If no exception occurs during the execution of the try clause, Python will execute the statement following the else statement.
Use except without any exception type, this is not a good way, we can not identify specific exception information through the program, because it catches all exceptions.
Note: The existence of the else statement must be based on the existence of the except statement. Using the else statement in a try statement without an except statement will cause a syntax error.

6. The raise statement
Python uses the raise statement to raise a specified exception. E.g:

try:
    raise NameError('HiThere')
except NameError:
    print('An exception flew by!')
    
# An exception flew by!

Practice question
1.

import random
x=random.randint(0,100)
i=1
while 1:
  tem = input("猜一个1-100之间的数字")
  print('第'+ str(i) +'次猜测')
  try:
      #type(temp)==int
      temp=int(tem)
  except Exception:
      print("输入无效")
      i+=1
      continue
  if temp > x:
      print("太大了")
  elif temp<x:
      print("太小了")
  else:
      print("恭喜你猜对了,这个数是:" + str(x))
  i+=1

Guess you like

Origin blog.csdn.net/m0_45672993/article/details/107555696