Home  >  Article  >  Backend Development  >  python study notes-error handling

python study notes-error handling

黄舟
黄舟Original
2017-01-17 14:17:591031browse

There are many ways to handle errors in the program. One is to agree on the error code, and then use the returned error code to determine whether an error occurred and the cause of the error.


But doing this can easily mix the correct return value and error code, and you have to write a lot of code to distinguish them, which is very inconvenient. In addition, once something goes wrong, you need to report it to the next level one level at a time until you know that there is another level that can handle it.


The more mature approach is try...except...finally...this set of error handling mechanisms. This mechanism does not interfere with normal return values. At the same time, there is no need to manually report one level at a time, but only one level of capture and processing is required.


Code:

try:
print open("Demo.py", 'r')
n = 1 / 0
except ZeroDivisionError, e:
print "zeroDivisionError", e
except ValueError, e:
print "ValueError", e
else:
print "No Error catched"
finally:
print "finally"

There are several points to note when using error handling:


Yes Write multiple excepts to catch multiple exceptions


The parent class exception can catch the exception of the subclass, and the exception that has been caught will not be passed to other exceptions.


You can use else to handle the situation where there is no exeption


finally will be executed regardless of whether there is an error or not.


Types of Build-in Exception

The inheritance relationship of Python (2.x) built-in Exception is shown in the figure below:

The class hierarchy for built-in exceptions is:
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StandardError
| +-- BufferError
| +-- ArithmeticError
| | +-- FloatingPointError
| | +-- OverflowError
| | +-- ZeroDivisionError
| +-- AssertionError
| +-- AttributeError
| +-- EnvironmentError
| | +-- IOError
| | +-- OSError
| | +-- WindowsError (Windows)
| | +-- VMSError (VMS)
| +-- EOFError
| +-- ImportError
| +-- LookupError
| | +-- IndexError
| | +-- KeyError
| +-- MemoryError
| +-- NameError
| | +-- UnboundLocalError
| +-- ReferenceError
| +-- RuntimeError
| | +-- NotImplementedError
| +-- SyntaxError
| | +-- IndentationError
| | +-- TabError
| +-- SystemError
| +-- TypeError
| +-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning

Of course we can also Customize a class, for example:

class MyException(StandardException):

Of course, it is recommended to use Build-in Exception. We only customize the Exception when we cannot find the Exception we need in the Exception in Build-in.


To throw a custom Exception use the following syntax:

raise MyException("this is my Exception")

In the test code, we can print exception directly when handling Exception. However, it may not be appropriate to directly print logs in actual production code. We can use logging.exception(msg) to print errors to the log through simple configuration. How to correctly use Python's built-in logging module can be introduced in another article.

The above is the content of python study notes-error handling. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn