1.1 Error Handling1.1.1 Try
>>> Try:
... print (' Try ... ')
... R = 10/0
... print (' Result: ', R)
... except Zerodivisionerror as E:
... print (' except: ', E)
... finally:
... print (' Finally ... ')
... print (' END ')
...
Try ...
Except:division by Zero
Finally ...
END
when we think that some code may be wrong, you can run the code with a try, and if you do something wrong , the subsequent code will not continue , but instead jump directly to the error-handling code, except statement block , after executing except , if there is a finally statement block, then execute the finally statement block , Execution is complete.
finally statement blocks whether or not they are executed except , it will be executed. .
define multiple except at the same time
>>> Try:
... print (' Try ... ')
... r = 10/int (' a ')
... print (' Result: ', R)
... except ValueError as E:-- exception 1
... print (' ValueError: ', E)
... except Zerodivisionerror as E:-- exception 2
... print (' except: ', E)
... else:--execute else without exception
... print (' no error ')
... finally:
... print (' Finally ... ')
... print (' END ')
...
Try ...
Valueerror:invalid literal for int () Withbase: ' A '
Finally ...
END
Spanning multiple layers of calls
One great benefit of using try...except to catch errors is that you can cross multiple calls, such as the function main () call foo (), andfoo () call Bar (), the result bar () is wrong, and as long as main () is captured, it can be processed.
>>> def foo (s):
... return 10/int (s)
...
>>> def Bar (s):
... return foo (s)
...
>>> def main ():
... try:
... bar (' 0 ')
... except Exception as E:
... print (' Error: ', E)
... finally:
... print (' Finally ... ')
...
>>> Main ()
Error:division by Zero
Finally ...
Just capture the error at the right level .
1.1.2 Call Stack
[email protected] python]# cat err.py
#!/bin/bash/python
#-*-Coding:utf-8-*-
def foo (s):
return 10/int (s)
def bar (s):
return foo (s) * 2
def main ():
Bar (' 0 ')
Main ()
[email protected] python]# python err.py
Traceback (most recent):
File "err.py", line A, in <module>
Main ()
File "err.py", line one, in main
Bar (' 0 ')
File "err.py", line 8, in bar
return foo (s) * 2
File "err.py", line 5, in Foo
return 10/int (s)
Zerodivisionerror:division by zero- the end is the root of the error
1.1.3 Log Errors
Catch the error, log the error stack, and let the program continue to run.
Python 's built-in logging module makes it very easy to log error messages.
[email protected] python]# cat err_logging.py
#!/usr/bin/python
#-*-Coding:utf-8-*-
Import logging
def foo (s):
return 10/int (s)
def bar (s):
return foo (s) * 2
def main ():
Try
Bar (' 0 ')
Except Exception as E:
logging.exception (e)
Main ()
Print (' END ')
[email protected] python]# python err_logging.py
ERROR:root:division by Zero
Traceback (most recent):
File "err_logging.py", line +, in main
Bar (' 0 ')
File "err_logging.py", line ten, in bar
return foo (s) * 2
File "err_logging.py", line 7, in Foo
return 10/int (s)
Zerodivisionerror:division by Zero
END
1.1.4 Throw Error
try to use python built-in error types .
error is class , capturing an error is capturing the class an instance of .
Define an error classand choose a good inheritance relationship.
>>> class Fooerror (ValueError):
... pass
...
>>> def foo (s):
... n = Int (s)
... if n = = 0:
... raise Fooerror (' Invalid value:%s '% s)
... return 10/n
...
>>> foo (' 0 ')
Traceback (most recent):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in Foo
__main__. Fooerror:invalid value:0-- self-defined error
Another way of handling errors -- wrong on the throw
>>> def foo (s):
... n = Int (s)
... if n = = 0:
... Raise ValueError (' Invalid value:%s '%s ')--python built-in error
... return 10/n
...
>>> def Bar ():
... try:
... foo (' 0 ')
... except ValueError as E:
.. print (' ValueError ')
... raise--theraise statement throws the current error as if it had no arguments .
...
>>> Bar ()
ValueError
Traceback (most recent):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in bar
File "<stdin>", line 4, in Foo
Valueerror:invalid value:0
in fact, this method of error treatment is not only not sick, but also quite common. The purpose of capturing errors is simply to record and facilitate follow-up. However, because the current function does not know what to do with the error, the most appropriate way is to continue to throw up and let the top-level caller handle it. If an employee can't handle a problem, throw it to his boss, and if his boss can't handle it, throw it all the way, and end up throwing it at the CEO's disposal.
Raise an error in except, you can also convert one type of mistake to another type
>>> Try:
... 10/0
... except Zerodivisionerror:
... raise valueerror (' input error ')
...
Traceback (most recent):
File "<stdin>", line 2, in <module>
Zerodivisionerror:division by Zero
During handling of the above Exception,another exception occurred:
Traceback (most recent):
File "<stdin>", line 4, in <module>
Valueerror:input Error
This article is from the "90SirDB" blog, be sure to keep this source http://90sirdb.blog.51cto.com/8713279/1826213
Python Error Handling