Python Learning note __8 error, debug, and test __8.1 error handling

Source: Internet
Author: User
Tags stdin

# This is a learning note for the Liaoche teacher Python tutorial

1. Overview

When we run a program or write a function, the system returns an error message after an error occurs. We can make the error message clearer by some mechanism.

1.1. Try

The format of the try mechanism is try...except...finally.

Try: # try: Run this code, if the code is wrong, execute except

Print (' Try ... ')

r = 10/0

Print (' Result: ', R)

except Zerodivisionerror as E: # except: captures the specified error type and assigns a value to the variable e . except can have multiple

Print (' except: ', E)

finally: # When the try or except finishes executing, the finally

Print (' finally ... ')

Attention:

Python's errors are also class, and all of the error types inherit from baseexception , so in use except It is important to note that it not only captures this type of error, but also "clean sweep" its subclasses . For example:

Try:
Foo ()
exceptValueError ase:
Print (' ValueError ')
exceptUnicodeerror ase:
Print (' Unicodeerror ')

second except unicodeerror Span style= "Font-size:12px;color: #DD0055; background: #FAFAFA" >unicodeerror is ValueError except was captured.

1.2. Call stack

$ Python3 err.py

Traceback (most recent):

File "err.py", line one, in <module>

Main ()

File "err.py", line 9, in main

Bar (' 0 ')

File "err.py", line 6, in bar

return foo (s) * 2

File "err.py", line 3, in Foo

return 10/int (s)

Zerodivisionerror:division by Zero

The call stack is the error message returned by the system itself. Look at the call stack, from the top down. The last three lines indicate the source of the error

1.3. Error recording

If you do not catch an error, you can have the Python interpreter print out the error stack, but the program is finished.

We can also catch the error, print out the error stack, and then analyze the cause of the error and let the program continue.

Python's built-in logging module makes it very easy to log error messages.

Import logging

def foo (s):

return 10/int (s) # source of Errors

def bar (s):

return foo (s) * 2

def main ():

Try

Bar (' 0 ') # Main ( ) calls bar()andBar () calls foo ().

Except Exception as E:

logging.exception (e)

Main ()

Print (' END ')

Because there are logging.exception (e). After the. py file is executed. will continue to print out "END"

1.4. Throw Errors

The error is class, and capturing an error is capturing an instance of the class . Therefore, the error is not generated in a vacuum, but intentionally created and thrown . The thrown error can be defined either as a python built-in function or as defined by our own

1 , the first type throws:

# err_raise.py

Class Fooerror (ValueError): # defines an error class

Pass

def foo (s):

n = Int (s)

If n==0:

Raise Fooerror (' Invalid value:%s '% s) # throws its own defined error class

Return 10/n

foo (' 0 ') # calling Functions

2, the second kind throws:

# err_reraise.py

def foo (s):

n = Int (s)

If n==0:

raise ValueError (' Invalid value:%s '% s) # throws valueerror error

Return 10/n

def bar ():

Try

Foo (' 0 ')

except ValueError as E:  # Catch Error

Print (' valueerror! ')

Raise # Raise throws the current error without parameters. Because foo ()is called, it is thrown to foo ()

Bar () # calling Functions

valueerror! # except after catching the error Print

Traceback (most recent):   # throws an error as it is, in the form of a protocol stack

File "<stdin>", line 1, in <module>

File "<stdin>", line 3, in bar

File "<stdin>", line 4, in Foo

valueerror:invalid value:0 # foo () throws a catch error

1.5. Incorrect conversion

Raise an error in except to convert one type of mistake to another type

Try

10/0

Except Zerodivisionerror:

Raise ValueError (' Input error! ')


Python Learning note __8 error, debug, and test __8.1 error 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.