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 isq
So 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
Oncetry
The content in the block is abnormal.try
The content after the block is ignored,PythonWill lookexcept
There 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:
Setexcept
Change the valueException
Class 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