Exception Handling in python advanced tutorial, python advanced tutorial

Source: Internet
Author: User

Exception Handling in python advanced tutorial, python advanced tutorial

Exception Handling is indispensable in project development. Exception Handling helps people debug and makes it easier for people to locate bugs Through richer information. Exception Handling can also improve program fault tolerance.

We mentioned a StopIteration exception when talking about circular objects. This exception is an error when the circular objects exhaust all elements.

Let's take it as an example to describe the Exception Handling of BenQ.

A program containing exceptions:
Copy codeThe Code is as follows:
Re = iter (range (5 ))

For I in range (100 ):
Print re. next ()

Print 'hahahahaha'

First, we define a loop Object re, which will carry out five cycles, each time using an element of the sequence.

In the subsequent for loop, we manually call the next () function. When the loop reaches 6th times, re. next () does not return any more elements, but throws a (raise) StopIteration exception. The entire program will be interrupted.

We can modify the above abnormal programs until they are perfect Without bugs. On the other hand, if we know the possible mistakes and possible types of mistakes when writing a program, we can define an emergency plan for this exception type.
Copy codeThe Code is as follows:
Re = iter (range (5 ))

Try:
For I in range (100 ):
Print re. next ()
Optional t StopIteration:
Print 'here is end', I

Print 'hahahahaha'

In the try section, we add the error-prone part. We can keep up with limit t to explain what the program should do when the try clause StopIteration occurs. If no exception occurs, the Skip T section is skipped.

Then, the program continues to run, rather than being completely interrupted.

The complete syntax structure is as follows:

Copy codeThe Code is as follows:
Try:
...
Except t exception1:
...
Except t exception2:
...
Except t:
...
Else:
...
Finally:
...

If an exception occurs in a try, the execution exception will be assigned and the execution will fail. Exception layer-by-layer comparison, check whether it is prediction1, prediction2. .. until you find its ownership and execute the corresponding statement in limit T. If there is no parameter after limit T, all exceptions are handled by this program. For example:
Copy codeThe Code is as follows:
Try:
Print (a * 2)
Handle t TypeError:
Print ("TypeError ")
Except t:
Print ("Not Type Error & Error noted ")

Because a is not defined, it is NameError. The exception is eventually caught by the progress T: part of the program.

If an exception cannot be handed over to an appropriate object, the exception will continue to be thrown to the upper layer until it is captured or the main program reports an error. For example, the following program

Copy codeThe Code is as follows:
Def test_func ():
Try:
M = 1/0
Failed t NameError:
Print ("Catch NameError in the sub-function ")

Try:
Test_func ()
Except t ZeroDivisionError:
Print ("Catch error in the main program ")

The try... limit t... structure of the subroutine cannot handle the corresponding error divided by 0, so the error is thrown to the upper-layer main program.

If there is no exception in try, the limit t part will be skipped and the else statement will be executed.

Finally is the last thing to do regardless of whether there are exceptions.

The process is as follows,
Copy codeThe Code is as follows:
Try-> exception-> wait t-> finally

Try-> no exception-> else-> finally

Throw an exception

You can also write an example to throw an exception:
Copy codeThe Code is as follows:
Print 'lala'
Raise StopIteration
Print 'hahahaha'

This example does not have any practical significance. Only to illustrate the role of raise statements.

StopIteration is a class. When an exception is thrown, an intermediate link is automatically generated, which is an object of StopIteration. Python actually throws this object. Of course, you can also generate an object by yourself:
Copy codeThe Code is as follows:
Raise StopIteration ()

Summary

Try:... failed t exception:... else:... finally :...
Raise exception


Python exception handling

Try to use either writable T or finally, and use writable t instead of finally.

Handling exceptions in the python tutorial

We recommend that you adjust the format and then ask questions.

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.