A day skills: they get to know one article Python errors and exceptions

Python code to write a small partner will inevitably encounter code execution errors and exceptions, and without loss of detail on this popular summarize python errors and exceptions.

To throw two questions:

  • What is Python errors and exceptions?

  • Python how to handle errors and exceptions?

1, a syntax error

Syntax error  may be the most frequently encountered beginner, familiar images such as the following:

<span><span style="font-size: 15px;">SyntaxError: invalid syntax</span></span>

Syntax errors, also known as parsing errors, another brother would ask what is wrong resolve?

In simple terms are the basic grammatical structure wrong, such as: multi-tasking into a single line, for loop did not add ':' and so on.

as follows:

Multitasking into a single line

loop did not increase for ':'

The above example can be seen, for grammatical errors, python parser output error of the line, and an arrow mark in the wrong place found first.

2, abnormal

After familiar with python syntax, syntax errors can be avoided, but the code is often abnormal  (Exception).

Or two problems:

  • What anomaly?

Python with  the exception object  (exception object) to indicate anomalies.

After an error is encountered, an exception is thrown.

If the exception object has not been processed or captured, the program will use the so-called  back  (traceback, wrong information) terminated.

  • Abnormal and grammatical errors What difference does it make?

Error: it refers to the code that does not comply with an interpreter or compiler syntax

Exception: it refers to incomplete, invalid input or calculation errors

About abnormalities, for example:

<span><span style="font-size: 15px;">Print('hello world')</span></span>

This line appeared abnormal, because Print the lowercase p should:

python thrown type: NameError, that is the wrong name.

Examples of other exceptions:

We can see, there are different types of abnormal, after an exception occurs, the type name will be printed. These are the python built-in exceptions, users can also customize the anomaly is not elaborated here.

3, try ... except ... statement

There python programming experience will know, python inside a  try ... except ...  statement to handle exceptions.

A look at an example of exception handling:

Look, we are perfectly capture the abnormal program.

Binding the example above, the exception processing rule: execute the statements in the try block, an error code in the processor except code block, except to remind throws exception ZeroDivisionError Coder, the error code is zero not as a dividend.

except the back may not add exception type will catch all exceptions occur:

We can  try ... except ...  the principles summarized in a few points:

  • First, the try clause ((multi-line between try and except keywords) statement)

  • If no exception occurs, the except clause is skipped and complete execution of the try statement

  • If an exception occurs during execution of the try clause, the remaining portion is skipped. Then, after the code if the type of the exception and exception matches behind except keyword, the except clause is executed, and then proceed to try statement

  • And if abnormality occurs except clause does not match the specified abnormality, it is transferred to the outside of the try statement; if the handler was not located, then it is an unhandled exception, execution stops and displays a message shown above

4, except clause plurality

Above  try ... except ...  statement only deals with an exception if I want to match more than a few types of exceptions, how to do it?

Here it is necessary  more than one except clause  to help, for example:

An exception is thrown ZeroDivisionError

TypeError exception is thrown

Above we used two except, matching ZeroDivisionError and TypeError these two exceptions, the first code to capture the ZeroDivisionError, the second paragraph of the code captured TypeError exception, had not tainted.

Of course, you can also write:

Except it is to use a plurality of capture abnormal changes into the back of the type except tuple.

In summary, for more than one except clause, it can be summarized as follows:

  • A   try   statement may have more than one except clause, to specify a different exception handling procedures
  • Most will execute a handler

  • Only exception handler process corresponding try clause occurred without processing the same   try   exception statement inside another handler
  • A plurality of abnormality except clause may be named parenthesized tuple

5、try...except Exception as e语句

We often look at such wording:

try...except Exception as e

Where e represents what does it mean?

Another example:

By way of example it can be known, e output exception type.

In other words,  Exception matches all exceptions, the exception name assigned to the E  . Of course, this does not have to be e, you can take any variable names, but agreed to write nothing more commonly known.

6, try ... except ... finally statement

try ... except ... finally statement may not be so common, but it is very useful.

If I want to open a txt file with python, then read, write, and finally close the file object. This is a normal process, if I want to catch the exception code in the process, but also to ensure whether or not there is an exception, eventually have to close the file.

This time it is used finally, look at the following example:

The above code, both catch the exception, eventually closed the file object.

The role finaly that, regardless of whether or not except exception is caught, finally back code will be executed, try to obtain the resources, finally releasing resources to ensure the finishing touches.

7, with ... statement

with ... statement is shorthand for try-finally statement, you can replace the function of try-finally.

Expression open ( 'poem.txt') return is assigned to a variable of type _io.TextIOWrapper f.

You can use this file with variable operating statement block.

After execution with this structure, f closes automatically comes with the equivalent of a finally.

8, summary

This article detailed and clearly explained the concept in Python and handling errors and exceptions, showing the specific use try ... except, try ... finally, with ... etc sentence through specific case, hoping to help am confused beginner

Guess you like

Origin www.cnblogs.com/7758520lzy/p/12653799.html