1. Try & except
Original program:
1 ImportMath2 3 whileTrue:4Text = Raw_input ('>')5 ifText[0] = ='Q':6 Break7x =float (text)8y =math.log10 (x)9 Print "log10 ({0}) = {1}". format (x, y)
View Code
This code receives the input of the command line, computes its logarithm and outputs it when the input is a number, until the input value is so q
far.
However, when you enter 0 or negative numbers, you will get an error.
The Modified program:
ImportMath whileTrue:Try: Text= Raw_input ('>') ifText[0] = ='Q': Breakx=float (text) y=math.log10 (x)Print "log10 ({0}) = {1}". Format (x, y)exceptValueError:Print "The value must be greater than 0"
View Code
Once the try
content in the block has an exception, the try
content behind the block is ignored, andPython will look for any content that is there, and if it does, except
executes the corresponding block, without throwing the exception.
Operation Result:
>-1 Thevalue must is greater than 0> 0the value must be greater than 0> 1log10 (1.0) = 0.0> Q
View Code
Catch all types of errors:
except
change the value to Exception
class to catch all exceptions.
ImportMath whileTrue:Try: Text= Raw_input ('>') ifText[0] = ='Q': Breakx=float (text) y= 1/math.log10 (x)Print "1/log10 ({0}) = {1}". Format (x, y)exceptException:Print "Invalid value"
View Code
Operation Result:
> 1Invalid value> 0invalid value> 1Invalid value> 21/log10 (2.0) = 3.32192 809489> Q
View Code
Further refinement of the program:
ImportMath whileTrue:Try: Text= Raw_input ('>') ifText[0] = ='Q': Breakx=float (text) y= 1/math.log10 (x)Print "1/log10 ({0}) = {1}". Format (x, y)exceptValueError:Print "The value must be greater than 0" exceptZerodivisionerror:Print "The value must not being 1" exceptException:Print "Unexpected error"
View Code
Operation Result:
> 1 not being 1>-1 Thevalue must is greater than 0> 0the value must be greater than 0> Q
View Code2. Finally
The contents of the finally block are always executed, regardless of whether the try block is not an exception, and are executed before the exception is thrown, so it can be used as a security guarantee, such as ensuring that open files are 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< C15/>3 finally: 4 print ' finally was called. ' Zerodivisionerror:integer division or modulo by zero
If the exception is caught, it is executed 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
01Python Base _09 exception