Exception handling for advanced python tutorials

  • 2020-04-02 14:02:48
  • OfStack

Exception handling is essential in project development. Exception handling helps people debug, making it easier to find bugs with more information. Exception handling can also improve your program's fault tolerance.

When we talked about circular objects earlier, we mentioned a StopIteration exception, which is an error that is reported when the circular object exhausts all the elements.

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

A program that contains exceptions:


re = iter(range(5)) for i in range(100):
    print re.next() print 'HaHaHaHa'

First, we define a loop object re that loops five times, using one element of the sequence each time.

In the for loop that follows, we manually call the next() function. When the loop reaches the sixth pass, re. Next () does not return an element, but instead raises an (raise)StopIteration exception. The entire program will be interrupted.

We can modify the above exception procedures until perfect without bugs. But on the other hand, if we're writing a program, knowing that we're going to make mistakes and what kind of mistakes we're going to make, we can define a "contingency plan" for that type of exception.


re = iter(range(5)) try:
    for i in range(100):
        print re.next()
except StopIteration:
    print 'here is end ',i print 'HaHaHaHa'

In the try segment, we put in the fallible parts. We can follow except to illustrate what the program should do if a StopIteration occurs on a statement in the try section. If no exception occurs, the except part is skipped.

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

The complete syntax is as follows:


try:
    ...
except exception1:
    ...
except exception2:
    ...
except:
    ...
else:
    ...
finally:
    ...

If an exception occurs in the try, the exception attribution is performed, except. The anomaly layers were compared to see if it was exception1, exception2... Until it is found, execute the statement in the corresponding except. If except is followed by no arguments, it means that all exceptions are passed to this program. Such as:


try:
    print(a*2)
except TypeError:
    print("TypeError")
except:
    print("Not Type Error & Error noted")

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

If the exception cannot be handed over to the appropriate object, the exception will continue to be thrown at the top level until it is caught or causes an error to be reported by the main program. Like 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")

Subroutine try... Except... The structure cannot handle the corresponding dividing by 0 error, so the error is thrown to the upper main program.

If there are no exceptions in the try, the except part is skipped and the statement in the else is executed.

Finally is something you end up doing with or without an exception.

The process is as follows,


try-> abnormal ->except->finally try-> There is no abnormal ->else->finally

An exception is thrown

We can also write our own example of throwing an exception:


print 'Lalala'
raise StopIteration
print 'Hahaha'

This example doesn't have any practical meaning. Just to illustrate what the raise statement does.

StopIteration is a class. When an exception is thrown, there is automatically an intermediate section that generates an object with StopIteration. What Python actually throws is this object. Of course, you can also generate your own objects:


raise StopIteration()

conclusion

Try:... Except the exception:... The else:... Finally:...
Raise the exception


Related articles: