Python errors and exception Codes

Source: Internet
Author: User

Python errors and exception Codes

Errors in programs are generally called bugs, which are undeniable. This is almost always a programmer's mistake...

A programmer's life is always accompanied by one thing-debugging (error detection and Exception Handling ). The most terrible thing is: not only do you have to change yourself, but others also need to change... 10 thousand grass mud horses rushed over!

Error

Program errors are classified into three types:

  • Syntax Error
  • Logical error
  • Runtime error

Syntax Error

Syntax errors (also known as parsing errors): errors caused by noncompliance with the syntax structure of the language (the program cannot be compiled or run properly ).
In a compilation language (for example, C ++), a syntax error occurs only during the compilation period. The Compiler requires that all the syntaxes be correct before normal compilation. However, for literal translation languages (such as Python), syntax errors may occur at runtime, and it is not easy to distinguish between syntax errors and semantic errors.

Common Python syntax errors include:

  • Missing some necessary symbols (colons, commas, or parentheses)
  • Incorrect keyword spelling
  • Incorrect indent
  • Empty statement block (pass statement is required)

For example, write such a condition judgment statement:

>>> if n < 5 File "<stdin>", line 1  if n < 5      ^SyntaxError: invalid syntax

Because the if statement lacks a colon (:) and does not conform to the Python syntax, the program cannot run normally.

Logical error

Logical error (also known as Semantic Error): indicates that the execution result of a program is inconsistent with the expectation (the program can run normally without Crash ).
Different from syntax errors, logical errors are correct in terms of syntax, but unexpected output or results may not be immediately discovered. The only manifestation of a logical error is the incorrect running result.

Common logical errors include:

  • Operator priority is not considered weekly
  • Incorrect variable name usage
  • The statement block indentation level is incorrect.
  • An error occurred in the Boolean expression.

For example, to calculate the average of two numbers:

>>> Def average (a, B):... return a + B/2 # Should Be (a + B)/2... >>>

Although the program can run normally, parentheses are missing in the Code. The calculation result is incorrect because of the operator priority (multiplication, division, and addition and subtraction.

Runtime error

Runtime error: indicates that the program can run, but an error occurs during running, resulting in unexpected exit.
When the program stops due to a running error, it is usually said that the program crashes. In Python, such a runtime error is called an exception.

Some runtime errors in Python:

  • Use an undefined identifier (NameError)
  • Division 0 (ZeroDivisionError)
  • The opened file does not exist (FileNotFoundError)
  • The imported module is not found (ImportError)

For example, the divisor is 0:

>>> 5 / 0Traceback (most recent call last): File "<stdin>", line 1, in <module>ZeroDivisionError: division by zero

Whenever such a running error occurs, Python creates an exception object. If the error is not handled properly, a trace will be output to the error and some details about why the error occurs.

Built-in exception hierarchies

Python has many built-in exceptions, which are thrown when an error occurs.

In Built-in Exceptions, there is a complete hierarchy of built-in Exceptions:

BaseException
+ -- SystemExit
+ -- KeyboardInterrupt
+ -- GeneratorExit
+ -- Exception
+ -- StopIteration
+ -- StopAsyncIteration
+ -- ArithmeticError
| + -- FloatingPointError
| + -- OverflowError
| + -- ZeroDivisionError
+ -- AssertionError
+ -- AttributeError
+ -- BufferError
+ -- EOFError
+ -- ImportError
+ -- ModuleNotFoundError
+ -- LookupError
| + -- IndexError
| + -- KeyError
+ -- MemoryError
+ -- NameError
| + -- UnboundLocalError
+ -- OSError
| + -- BlockingIOError
| + -- ChildProcessError
| + -- ConnectionError
| + -- BrokenPipeError
| + -- ConnectionAbortedError
| + -- ConnectionRefusedError
| + -- ConnectionResetError
| + -- FileExistsError
| + -- FileNotFoundError
| + -- InterruptedError
| + -- IsADirectoryError
| + -- NotADirectoryError
| + -- PermissionError
| + -- ProcessLookupError
| + -- TimeoutError
+ -- ReferenceError
+ -- RuntimeError
| + -- NotImplementedError
| + -- RecursionError
+ -- SyntaxError
| + -- IndentationError
| + -- TabError
+ -- SystemError
+ -- TypeError
+ -- ValueError
| + -- UnicodeError
| + -- UnicodeDecodeError
| + -- UnicodeEncodeError
| + -- UnicodeTranslateError
+ -- Warning
+ -- DeprecationWarning
+ -- PendingDeprecationWarning
+ -- RuntimeWarning
+ -- SyntaxWarning
+ -- UserWarning
+ -- FutureWarning
+ -- ImportWarning
+ -- UnicodeWarning
+ -- BytesWarning
+ -- ResourceWarning

Note: This hierarchy is useful when an exception is caught or you decide which exception class to inherit.

Summary

The above is all the details about Python errors and Exception Code in this article, and I hope to help you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.