01Python basics _ 09 exception, 01Python basics _ 09

Source: Internet
Author: User

01Python basics _ 09 exception, 01Python basics _ 09
1. try & try t

Original program:

1 import math2 3 while True:4     text = raw_input('> ')5     if text[0] == 'q':6         break7     x = float(text)8     y = math.log10(x)9     print "log10({0}) = {1}".format(x, y)
View Code

This code receives the input from the command line. When the input is a number, calculate its logarithm and output it until the input value isqSo far.

However, when the input is 0 or negative, an error is returned.

Modified program:

import mathwhile True:    try:        text = raw_input('> ')        if text[0] == 'q':            break        x = float(text)        y = math.log10(x)        print "log10({0}) = {1}".format(x, y)    except ValueError:        print "the value must be greater than 0"
View Code

OncetryThe content in the block is abnormal.tryThe content after the block is ignored,PythonWill lookexceptThere is no corresponding content in it. If it is found, the corresponding block is executed. If it is not found, this exception is thrown.

Running result:

> -1the value must be greater than 0> 0the value must be greater than 0> 1log10(1.0) = 0.0> q
View Code

  Capture all types of errors:

SetexceptChange the valueExceptionClass to capture all exceptions.

import mathwhile True:    try:        text = raw_input('> ')        if text[0] == 'q':            break        x = float(text)        y = 1 / math.log10(x)        print "1 / log10({0}) = {1}".format(x, y)    except Exception:        print "invalid value"
View Code

Running result:

> 1invalid value> 0invalid value> -1invalid value> 21 / log10(2.0) = 3.32192809489> q
View Code

Further improved procedures:

import mathwhile True:    try:        text = raw_input('> ')        if text[0] == 'q':            break        x = float(text)        y = 1 / math.log10(x)        print "1 / log10({0}) = {1}".format(x, y)    except ValueError:        print "the value must be greater than 0"    except ZeroDivisionError:        print "the value must not be 1"    except Exception:        print "unexpected error"
View Code

Running result:

> 1the value must not be 1> -1the value must be greater than 0> 0the value must be greater than 0> q
View Code 2. finally

No matter whether the try block has any exceptions, the finally block content will always be executed and will be executed before an exception is thrown. Therefore, it can be used as a security guarantee, for example, to ensure that the opened file is closed.

try:    print 1 / 0finally:    print 'finally was called.'

Out: finally was called.

---------------------------------------------------------------------------ZeroDivisionError                         Traceback (most recent call last)<ipython-input-13-87ecdf8b9265> in <module>()      1 try:----> 2     print 1 / 0      3 finally:      4     print 'finally was called.'ZeroDivisionError: integer division or modulo by zero

If the exception is caught, run the following command at the end:

try:    print 1 / 0except ZeroDivisionError:    print 'divide by 0.'finally:    print 'finally was called.'out: divide by 0.     finally was called.
View Code

 

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.