Python Introductory Tutorial Series: first, exception handling

Source: Internet
Author: User

in the first few chapters, we have put the basic content of Python briefly, starting from this chapter, we are the introductory level of learning, mainly the rest of the content to say, mainly including exception handling, module use, function use, object-oriented, regular matching, database, network (crawler), Finally, we will have an advanced series of tutorials on machine learning.

exception handling, in the most popular words, is your program error, this error is divided into several kinds, some may be grammatical errors, such as how much you write less write wrong write characters, etc., there are logic errors, such as 1>2, grammatical error but logic error, for beginners, the most committed error is sloppy, That is, grammatical errors, the most rookie of the mistake is that you think your code can be so running, in fact, it is not so running, even you are staring at the code for a long time you do not know what is wrong, always think that the program is in accordance with 1, 2, 3 steps, in fact, according to 1, 3 steps, The 2nd step is not going to work anyway, which is why you may not be really clear about the structure of certain grammars.

Of course this does not mean that as long as you are careful, as long as you are very clear about the grammatical structure you will not make mistakes, the wrong moment is likely to occur, such as artificial intentional error operation, so the error is not scary, error-prone program is terrible,. The question is how we make our program strong and robust, and even if there are errors, we can continue to work instead of crashing.

Let's take a look at a few examples:

The first example is that the variable does not have a defined error, usually we do not need to define a variable name in the program, but can be used directly, there is no error, ah, why not here? For example, we define a string ' python ', usually we write str1 = ' python ', and we do not define STR1 first, in fact the string itself is an object, we define a Str1 object (object type unknown), It is then assigned a value (at this point the object type is explicitly a string), which is the correct syntax, and simply writing a str1 is an empty object with an unknown object type.

The second example is divided by the 0 error, the earth people know

The third syntax is malformed, SyntaxError is the only error message at compile time, that is, your program structure is wrong, here is the FOR syntax error .

The fourth error is the array out of bounds error, originally 3 things, you want to find the 4th must not find the error

The fifth error is that the dictionary is queried for a key that does not exist.

The sixth error is that there is no error in the file, which in all likelihood does not really exist, but the path is not written or wrong

Of course there are other errors, here just to cite a few common ones.

error detection and exception handling:

1, Try-except

2, try-finally

3, try-except-finally

What does that mean? Try-except is to put the possible error code into the try, that is, try to mean, if it is possible to make a mistake we give the solution in the except statement, of course there are several types of error, so this except can have several, However, it is important to note that the first match of a specific error can also be said of a small range of errors, and then in matching a wide range of errors, what is the reason? For example, error 1 contains error 2, then you first match error 1, then no matter what error 2 is no longer matched, that is, error 2 given the processing scheme will never reach, this is the logic error. Finally, the code in the finally is run whether or not an error occurs, so finally only one occurrence is allowed. There are 3 combinations of options.

Here is an example for you to look at, say more than a demo.

>>> Try:
... f = open (' Blah ', ' r ')
... except IOError, E:
... print ' could not open file: ', E
...
Could not open file: [Errno 2] No such file or directory

The remaining statement after the occurrence of an exception in a try statement block never arrives (and therefore never executes). Once an exception is thrown, you must decide where the control flow will arrive next. The remaining code is ignored, the interpreter will search for the processor, and once found, Start executing the code in the processor. if no suitable processor is found, then the exception is handed over to the caller, which means that the stack frame immediately returns to the to the previous one. If the processor is not found on the upper-level caller, the exception will continue to be forwarded upward until a suitable processor. If the corresponding processor is still not found at the top level, the exception is considered unhandled, and Python explains The tracker will display a trace return message and then exit.

examples of multiple except:

def safe_float (obj):
Try:
retval = float (obj)
except ValueError:
retval = ' could not convert non-number to float '
except TypeError:
retval = ' Object type cannot is converted to float '
return retval

to catch all exceptions:

the root of all errors is exception, which is at the top level.

Try:
:
Except Exception, E:
# error occurred, log ' e ', etc.

Although such code captures most exceptions, it is not a good Python programming style. One of the main reasons is that it does not take into account the underlying cause of the exception.

try :
:
Except Exception, E:
# error occurred, log ' e ', etc.

except ValueError:

...

This kind of writing is wrong, because no matter exception contains valueerror error, so ... The statements in will not run anyway.

Here's an episode, the Else statement can also be used in try-except, and if the error does not match, you can run the content in the Else statement.

Try
A
Except Myexception:b
Else:c
Finally:d

Try
Try_suite
Finally
Finally_suite #无论如何都执行

Combine all the different syntax styles that we've seen in this chapter that can handle exceptions:

Try:
Try_suite
Except Exception1:
Suite_for_exception1
Except (Exception2, Exception3, Exception4):
Suite_for_exceptions_2_3_and_4
Except Exception5, ARGUMENT5:
Suite_for_exception5_plus_argument
Except (Exception6, Exception7), Argument67:
Suite_for_exceptions6_and_7_plus_argument
Except
Suite_for_all_other_exceptions
Else
No_exceptions_detected_suite

finally:
Always_execute_suite

for More on exception capture processing, refer to the tenth chapter of Python core programming, thank you.

Python Introductory Tutorial Series: first, exception handling

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.