In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the "python exception handling try method tutorial" related knowledge, in the actual case operation process, many people will encounter such a dilemma, and then let the editor lead you to learn how to deal with these situations! I hope you can read it carefully and be able to achieve something!
A brief introduction to exception handling
When we write program code, we often fail the whole program directly because of a small problem.
What are the benefits of exception handling for our testing? I believe students who have done automation all know that our use cases are all executed one by one, for example, we have hundreds of program use cases, and one use case causes a program exception due to data reasons. Then the rest will stop working. In such a situation, we should throw out the problem caused by this data and deal with this exception.
We can use tryexcept to handle exceptions.
structure
Put statements that may report errors into try:, and then use except to handle exceptions. Each try must have at least 1 except.
If an error may occur in the statement, we can know which exceptions to report. We need to follow the exception name after except.
You can also use universal exception Exception, which can catch any exception
All the standard exception classes of python: see the end of the article
Example 1: handling the specified error exception type
If we know which errors will be reported, we can catch and handle them directly, but if the name of the catch exception is incorrect, the program will also report an error.
First we print an error with an undeclared / initialized object (no attributes), and then print a piece of data that can normally be executed.
Print (aa) print ('bb')
Print the result
Traceback (most recent call last):
File "C:\ Users\ Zhang Tianzhi\ PycharmProjects\ pythonProject\ test\ lianxi\ 111.py", line 6, in
Print (a)
NameError: name 'a'is not defined
Obviously print ("bb") is not executed, so we now add try to the part where we may or know to report an error: and specify the NameError as to f variable with except, and print out the error
Try: print (aa) except NameError as f: print (f) print ('bb')
Print the result
Name 'aa' is not defined
Bb
As you can see, the program prints out the error message and then executes print ("bb")
What if I open the wrong file? I don't know the wrong name for opening the file, how can I deal with it at this time?
Try: open ('ztc.txt','r') except NameError as f: print (f) print (' bb')
Print the results:
It's actually an output error file. I can't find the exception name correctly with Nameerror.
Traceback (most recent call last): File "C:\ Users\ Zhang Tianzhi\ PycharmProjects\ pythonProject\ test\ lianxi\ 111.py", line 2, in open ('ztc.txt','r') FileNotFoundError: [Errno 2] No such file or directory:' ztc.txt'
If you encounter such a situation, please see example 2.
Example 2: omnipotent exception handling
As we said in example 1, when we can determine what type of error will be reported, we can specify this error type to deal with it. Of course, in many cases, we will encounter a lot of unknown exceptions, and it is impossible to predict all the exceptions, so we can directly use the universal exception Exception.
Try: open ('ztc.txt','r') except Exception as f: print (f) print (' bb')
Print the results:
Exception can handle any wrong type of exception in our try.
[Errno 2] No such file or directory: 'ztc.txt'
Bb
Example 3: Rutty.. finale...
Try...finally... Whether our program encounters an error, the code must be executed
What scenarios can be used?
For example, if we link to the database, in order to operate the database, if the program reports an error or not, we must close the database.
For example, if we open an excel or txt document, we must close the document to write data, regardless of whether the error is reported or not.
First of all, let's take a look at a normal situation.
Try: F = open ('ztc.json','r') finally: f.close () print (' closed')
Print the result
Has been closed.
If you open the file and don't wait for the file to be closed, you will report an error.
Try: F = open ('ztc.json','r') print (aaa) finally: f.close () print (' closed')
Print the result
Traceback (most recent call last):
File "C:\ Users\ Zhang Tianzhi\ PycharmProjects\ pythonProject\ test\ lianxi\ 111.py", line 3, in
Print (aaa)
NameError: name 'aaa' is not defined
Has been closed.
Looking at the code above, it is obvious that the program reported an error when printing print (aaa), but still closed the open file.
Appendix:
Exception name describes the base class of all BaseException exceptions SystemExit interpreter requests exit KeyboardInterrupt user interrupts execution (usually input ^ C) Exception general error base class StopIteration iterator has no more values GeneratorExit generator (generator) exception occurs to notify exit SystemExitPython interpreter request exit all built-in standard exceptions of StandardError base class ArithmeticError all numerical calculation errors FloatingPointError floating point calculation error OverflowError numerical operation exceeds maximum Limit ZeroDivisionError by (or modulo) zero (all data types) AssertionError assertion statement failed AttributeError object does not have this property EOFError has no built-in input Reached EOF tag EnvironmentError operating system error base class IOError input / output operation failed OSError operating system error WindowsError system call failed ImportError import module / object failed KeyboardInterrupt user interrupted execution (usually input ^ C) LookupError invalid data query the base class IndexError sequence does not have this index (index) this key is not in the KeyError map MemoryError memory overflow error (not fatal for Python interpreter) NameError silent Ming / initialization object (no attributes) UnboundLocalError access uninitialized local variable ReferenceError weak reference (Weak reference) attempt to access garbage collected object RuntimeError general run time error NotImplementedError unimplemented method SyntaxErrorPython syntax error IndentationError indentation error TabErrorTab and space mixing SystemError general interpreter error TypeError when invalid type operation ValueError input invalid parameter UnicodeErrorUnicode related error UnicodeDecodeErrorUnicode decoding Error UnicodeEncodeErrorUnicode coding error UnicodeTranslateErrorUnicode conversion error Warning warning base class DeprecationWarning about deprecated features warning about constructing future semantics will change warning OverflowWarning old warning about automatically promoted to long integer (long) warning PendingDeprecationWarning about features will be discarded warning SyntaxWarning suspicious runtime behavior (runtime behavior) warning SyntaxWarning suspicious syntax warning UserWarning user code generation warning "python exception" This is the end of the introduction to the method course of try. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.