Python bug Terminator: Common error exception handling + + + debugging error code

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/suoyue_py/article/details/100064234

(A) Common errors

  1. Missing the colon that caused the error: At the end of if, else, else, while, class, def statement you need to add a colon: If you will be prompted forget to add "SyntaxError: invalid syntax" syntax error.
  2. The assignment operator = and comparison operators == confused : will prompt "SyntaxError: invalid syntax" syntax error.
  3. Structure of the code indentation errors : will prompt an error message such as "IndetationError: unexpected indent", " IndentationError: unindent does not match any outer indetation level" and "IndentationError: expected an indented block"
  4. Modify the value of the string and tuple being given
  5. The connection string and non-string : will prompt error "TypeError: Can not convert 'int ' object to str implicitly".
  6. In the string end to end forget quotes : will prompt error "SyntaxError: EOL while scanning string literal ".
  7. Variable or function name misspelled : will prompt error "NameError: name 'xxx' is not defined".
  8. It cited more than a list of the largest index : will prompt error "IndexError: list index out of range ".
  9. Use keywords as variable names : will prompt error "SystaxError: invalid syntax".
  10. Variable with no initial value on the use of value-added operator : will prompt error "NameError: name 'xxx' is not defined".
  11. Misuse increment and decrement operators : Error will prompt "SystaxError: invalid syntax".
  12. Forget the first argument is a method of adding self argument : will prompt error "TypeError: myMethod () takes 0 positional arguments but 1 was given".

(B) abnormal

1. The concept of abnormality
when the Python interpreter encounters an unexpected program behavior, it will output an exception (exception). For example encountered divide by zero, or open a file that does not exist and so on. You can also use the raise statement to throw an exception. When the Python interpreter encounters an unusual condition, it will stop running programs, and then display a trace (traceback) information.
2. Built abnormal
Python built-in exceptions defined in the exceptions module , the module will automatically loaded when the Python interpreter starts
the most common meaning of the following exception classes:
(. 1) BaseException: base class for all exceptions.
(2) SystemExit: exit request interpreter.
(3) KeyboardInterrupt: User interrupt execution.
(4) Exception: General Error base class.
(5) StopIteration: iterator no more value.
(6) GeneratorExit: Generator (generator) to inform the abnormal exit occurred.
(7) SystemExit: Python interpreter requested to exit.
(8) StandardError: all internal standard base class exception.
(9) ArithmeticError: All numerical errors base class.
(10) FloatingPointError: floating-point calculation error.
(11) OverflowError: the maximum value calculation exceeds the limit.
(12) ZeroDivisionError: error other (or modulus) of zero (all data types).
(13) AssertionError: assertion failed.
(14) AttributeError: object does not have this property.
(15) EOFError: no built-in input, a common mistake is to read a file, in addition, Ctrl + D will also trigger this exception.
(16) EnvironmentError: base class operating system errors.
(17) IOError: an input / output operation failed.
(18) OSError: operating system error.
(19) WindowsError: system call failed.
(20) ImportError: import module / object failed.
(21) KeyboardInterrupt: User Interrupt Executing (usually Ctrl + C).
(22) LookupError: invalid class data base queries.
(23) IndexError: Without this sequence index (index).
(24) KeyError: map does not have this key.
(25) MemoryError: memory overflow error (for Python interpreter is not fatal).
(26) NameError: not declare an object or not initialized object.
(27) UnboundLocalError: local access uninitialized variables.
(28) ReferenceError: garbage collection has been trying to access the object.
(29) RuntimeError: general runtime error.
3. try ... except the processing exception statement
try ... except statement is used in the output of the exception handling of the Python.
The syntax is:

try:
   <语句>
except [<异常的名称> [, <异常类的实例变量名称>]]:
   <异常的处理语句>
[else:
   <没有异常产生时的处理语句>]

Syntax brackets [] may be omitted in the
name of the exception may be blank, except statement represents all types of exception handling
exception name may be one or more
may be used a plurality of different except statement to handle different exception
else statement is a processing procedure when no abnormality occurs
example 4. exception class
whenever there is an exception to be output, the exception will create a class instance that inherits all the attributes exception classes. Each instance of an exception class, there is a args property. args attribute is a tuple format, this format may only contain tuple error message string (1-tuple), and may also contain two or more elements (2-tuple, 3-tuple , ...).
Different classes of exception, this format is different tuples.
The clear exception
try ... finally statement can be used as a clear dysfunction. Whether or not to fail in the try statements, finally statement will be run.
Note: try and except statements can be used with, try and finally statement can also be used with, but except with a finally statement can not be put together.
6. built-in exceptions assistance module

  • A, sys module
    using the sys module exc_info () function can be achieved abnormality information is currently being processed. exc_info () function returns a tuple, the tuple comprises three elements (type, value, specific information).

  • B, traceback objects
    using the sys module exc_info () function returns the value of the third element, and returns a traceback object. interface function traceback object may be captured, formatted, or the output of the tracking program Python stack (stack trace) information.
    traceback.print_exc (): This function calls sys.exc_info () to output the exception.

7. thrown

  • a, raise statement: Python using the raise statement throws a specified exception. E.g:
    >>>raise NameError('这里使用raise抛出一个异常')
    Traceback (most recent call last):
      File "<pyshell#13>", line 1, in <module>
        raise NameError('这里使用raise抛出一个异常')
    NameError: 这里使用raise抛出一个异常

raise only one parameter specifies to the thrown exception, the exception must be a class instance or abnormal (i.e. Exception subclass).
Tip: If you want to determine whether an exception is thrown and not want to deal with it, this time using the raise statement is the best option.

  • B, the end of the interpreter to run: the user can use the output SystemExit exception, to force the end of the Python interpreter running.
    Use sys.exit () function will output a SystemExit abnormal, sys.exit () function will end thread.
    To the end of normal operation of the Python interpreter preferably used os module _exit () function
  • c, leaving nested loops: If you want to leave the cycle of time, usually using the break statement. If one of the nested loop, break statement can only leave the innermost loop, but can not leave the nested loops, may be used at this time to leave the raise statement nested loops.

8. The user-defined exception class
in addition to built-in exceptions, Python also supports user-defined exceptions. Abnormal built user-defined exception no difference, but exceptions are defined in the built-in module exceptions. When the Python interpreter starts, exceptions module will be loaded in advance.
Python allows users to define their own exception classes, user-defined exception classes must be from any one of Python's built-in exception class derived from.
Users can also create custom exception class, then as a base class for other user-defined exception classes.
Exception classes are usually "Error" at the end, with the exceptions named as standard when creating

(C) Program Debugging

  • a, using assert statements
    by using the assert statement can help users to detect errors in the program code.
    assert statement syntax is:
    assert <Test Pattern> [parameter]
    test pattern was a return True or False program code.
    If the test code is returned true, the program code continues to run behind.
    If the test code returns false, assert statement will output a AssertionError exception. And assert the output statement [parameters], the error message as a string.

  • b, using the built-in variable __debug__

Python解释器有一个内置变量__debug__,__debug__在正常情况下的值是True。
>>> __debug__
True
当用户以最佳化模式启动Python解释器时,__debug__值为False。要使用最佳化模式启动Python解释器,须设置Python命令行选项-O。
语法格式:
if __debug__:
	if not (<测试码>):
		raise AssertionError [,参数]

(Iv) error code

The Python errno module, comprising a plurality of error code ( errno ) notation system (system symbol). errno module defined in integer error code returned by the operating system, and the system corresponding symbol.
When a user uses dir (errno) instruction, the system can obtain the error code symbols for all.
Here Insert Picture Description
Use os module of the strerror () function , an error code may be converted into a string description of the error codes. Error code error.E2BIG e.g. description string is 'Arg list too long'.
Here Insert Picture Description
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/suoyue_py/article/details/100064234