Python Errors and exceptions

Source: Internet
Author: User

GitHub Blog Portal
CSDN Blog Portal

Python error and exception syntax errors

The syntax error of Python, or it is called parsing fault, is often encountered by beginners, the following example:

while True print(‘Hello world‘)

You will receive the following error message:

The function print () is checked to have an error and is missing a colon (:) in front of it.
The parser points to the wrong line and marks a small arrow at the location of the first found error.

Abnormal

The run-time detected error is called an exception.
Cases:

print(1/0)4 + spam*3‘2‘ + 2

Exceptions appear in different types, which are printed as part of the information: the type in the example
There are Zerodivisionerror,nameerror and TypeError.

Exception handling

Python uses the try except statement to catch and handle exceptions.
Cases:

def div(a,b):    try:        return a/b    except ZeroDivisionError:        print("除数不能为0")div(3,0)
The Try statement works as follows:

First, execute the TRY clause (the statement between the keyword try and the keyword except)
If no exception occurs, the EXCEPT clause is ignored, and the try clause finishes after execution.
If an exception occurs during the execution of a try clause, the remainder of the try clause is ignored. If the type of the exception and
After the except name matches, the corresponding except clause is executed. The code after the last try statement is executed.
If an exception does not match any of the except, then the exception is passed to the upper try.

A try statement may contain multiple except clauses that handle different specific exceptions. At most only
A branch will be executed.
Handlers will only handle exceptions in the corresponding try clause, not other try processes
The exception in the sequence.
A except clause can handle multiple exceptions at the same time, and these exceptions will be placed in parentheses to become a
Tuples, for example:

except (RuntimeError, TypeError, NameError):
Try except also has an else optional clause

If this clause is used, it must be placed in all
After the except clause. This clause will be executed when no exception occurs in the TRY clause. For example:

def div(a,b):    try:        a/b    except ZeroDivisionError as Zero:        print("除数不能为0",Zero)    else:        print("没有捕获到异常")div(3,4)

It is better to use the ELSE clause than to put all the statements in a try clause, which avoids unexpected, except, and uncaught exceptions.

Exception handling does not only deal with exceptions that occur directly in the TRY clause, but also handle the clauses in the
The exception that is thrown in the function (even the indirectly called function). For example:

def this_fails():    x = 1 / 0    try:        this_fails()    except ZeroDivisionError as err:        print(‘捕获到异常:‘, err)
Exception handling

Python throws a specified exception using the Raise statement. For example:

raise NameError(‘HiThere‘)

Raise only one parameter specifies the exception to be thrown. It must be an instance of an exception or an exception class (that is, a subclass of Exception).
If you just want to know if this throws an exception and don't want to deal with it, then a simple raise statement can throw it again.

try:    raise NameError(‘HiThere‘)except NameError:    print(‘一个异常被抛出啦!‘)    raise

Python Errors and exceptions

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.