Python Advanced 08 Exception handling

Source: Internet
Author: User
Tags for in range throw exception

Exception handling

In project development, exception handling is essential. Exception handling helps people debug and, through richer information, make it easier for people to find where a bug is. Exception handling can also improve the fault tolerance of the program.

When we talked about the loop object before, we mentioned a Stopiteration exception, which was an error when the Loop object exhausted all the elements.

Let's take it as an example to illustrate the basic exception handling.

A program that contains exceptions:

Re = ITER (range (5)) for in range:    print ()  Print'hahahaha'

First, we define a cyclic object, re, which will loop 5 times, using one element of the sequence at a time.

In the subsequent for loop, we call the next () function by hand. When the loop is made to the 6th time, () no longer returns the element, but throws (raise) the stopiteration exception. The entire program will be interrupted .

We can modify the above exception program until the perfect no bug. But on the other hand, if we are writing a program, knowing that there are possible mistakes and possible types of errors, we can define "contingency plans" for that type of exception.

Re = ITER (range (5))try:    for in range         :Print ()except  stopiteration:    print'   ', Iprint'hahahaha'

In the Try program segment, we put in a section that is prone to mistakes. We can keep up with except to illustrate what the program should do if the statement in the Try section occurs stopiteration. If no exception occurs, the except section is skipped.

The program will then continue to run, instead of being completely interrupted.

The complete syntax structure is as follows:

Try :    ... except exception1:     ... except Exception2:
except: ... Else : ... finally : ...

If an exception occurs in a try, the attribution of the exception is performed, and the except is executed. Anomaly layer comparison, see if it is Exception1, exception2 ... until it finds its attribution, executes the statement in the corresponding except. If there are no parameters behind the except, then all exception are handed over to this program for processing. Like what:

Try :     Print (a*2) except TypeError:     Print ("TypeError") except :     Print ("notType Error & Error noted")

Since a is not defined, it is nameerror. The exception is eventually except: part of the program captures.

If the exception cannot be given to the appropriate object, the exception will continue to be thrown to the upper layer until it is captured or causes an error in the main program. such as the following program

 def   Test_func ():  try  : M  = 1/0  except   Nameerror:  print  ("  catch nameerror in the sub-function   " "  try  : Test_func ()  except   zerodivisionerror:  print  ( " catch error in the main program   ")  

Sub-Program try...except ... The structure cannot handle the corresponding error divided by 0, so the error is thrown to the upper master program.

If there is no exception in the try, then the except section skips and executes the statement in the else .

Finally, there are some things to do, whether or not there is an exception.

The process is as follows

try-> Abnormal->except->finally

Try-> No Abnormal->else->finally

Throw exception

We can also write an example of throwing an exception ourselves:

Print ' Lalala ' Raise stopiteration Print ' hahaha '

This example does not have any practical significance. Just to illustrate the role of the raise statement.

Stopiteration is a class. When an exception is thrown, it automatically has an intermediate link, which is an object that generates Stopiteration. What Python actually throws is this object. Of course, you can also build your own objects:

Raise Stopiteration ()

Python Advanced 08 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: 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.