Python (5) exception handling

1. Exception

1. What is an exception?

Even if the syntax of a python program is correct, some unexpected errors may occur at runtime. Errors detected at runtime are called exceptions. Some errors may not be fatal, but if the programmer handles exceptions well, the python interpreter will print the exception to the console and terminate the program.

2. Common exceptions

  • BaseException: base class for all exceptions
  • SystemExit: The interpreter requested to exit
  • KeyboardInterrupt: User interrupts execution (usually by typing ^C)
  • Exception: base class for general errors
  • StopIteration: the iterator has no more values
  • GeneratorExit: The generator (generator) has an exception to notify the exit
  • StandardError: base class for all built-in standard exceptions
  • ArithmeticError: base class for all numerical computation errors
  • FloatingPointError: floating point calculation error
  • OverflowError: Numerical operation exceeds maximum limit
  • ZeroDivisionError: division (or modulo) by zero (all data types)
  • AssertionError: Assertion statement failed
  • AttributeError: Object does not have this attribute
  • EOFError: No built-in input, reaching EOF marker
  • EnvironmentError: base class for operating system errors
  • IOError: input/output operation failed
  • OSError: Operating system error
  • WindowsError: system call failed
  • ImportError: Failed to import module/object
  • LookupError: base class for invalid data query
  • IndexError: No such index in the sequence (index)
  • KeyError: The key does not exist in the map
  • MemoryError: memory overflow error (not fatal to the Python interpreter)
  • NameError: undeclared/initialized object (has no properties)
  • UnboundLocalError: access to uninitialized local variable
  • ReferenceError: Weak reference attempted to access a garbage collected object
  • RuntimeError: Generic runtime error
  • NotImplementedError: Method not yet implemented
  • SyntaxError: Python syntax error
  • IndentationError: Indentation error
  • TabError: Mixing Tab and Space
  • SystemError: general interpreter system error
  • TypeError: Invalid operation on type
  • ValueError: Invalid parameter passed in
  • UnicodeError Unicode: related error
  • UnicodeDecodeError: Unicode decoding error
  • UnicodeEncodeError: Error encoding Unicode
  • UnicodeTranslateError: Error during Unicode translation
  • Warning: base class for warnings
  • DeprecationWarning: Warning about deprecated features
  • FutureWarning: A warning that the semantics of the constructed future will change
  • OverflowWarning: old warning about auto-promotion to long
  • PendingDeprecationWarning: A warning that the feature will be deprecated
  • RuntimeWarning: Warning of suspicious runtime behavior
  • SyntaxWarning: Suspicious syntax warning
  • UserWarning: Warning generated by user code

2. Handling exceptions

1. try...except...else...finally...syntax

Note : If an exception occurs in the try, the except clause will be called immediately, and the rest of the code in the try will not be executed.

        try:
            代码块(可能出现错误的语句)
        except 异常类型 as 异常名:
            代码块(出现错误以后的处理方式)
        except 异常类型 as 异常名:
            代码块(出现错误以后的处理方式)
        except 异常类型 as 异常名:
            代码块(出现错误以后的处理方式)
        else
            代码块(try没出错时要执行的语句)    
        finally:
            代码块(该代码块总会执行)    

        #try是必须的,else语句有没有都行,except和finally至少有一个    

2. Take a chestnut

number = int(input('请输入一个数字:'))#输入a时引发异常,程序终止
print(number)
print('运行结束!')

insert image description here

try:
    number = int(input('请输入一个数字:'))#输入a时打印异常,程序正常运行
    print(number)
except ValueError:
    print('输入了无效的数字', ValueError)
except Exception as e:
    print('输出错误', e)
else:
    print("try正常执行,没有异常发生...")
finally :
    print('运行结束!')#总会执行

insert image description here
insert image description here

3. Throwing an exception (raise)

1. Grammar

raise [SomeException [, args [,traceback]]
  • The first parameter, SomeException, must be an exception class, or an instance of an exception class.

  • The second parameter is the parameter passed to SomeException and must be a tuple. This parameter is used to pass useful information about the exception.

  • The third parameter traceback is rarely used and is mainly used to provide a traceback object.

name = input("请输入您的用户名:")
if name == "小明":
    raise ("黑名单用户,禁止登登录!")  # raise自定义自动抛出异常

insert image description here

Guess you like

Origin blog.csdn.net/shammy_feng/article/details/117063603