In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how python triggers and handles exceptions". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how python triggers and handles exceptions".
What is an anomaly?
The exception of the program means that some unexpected events occur while the program is running, and these events prevent the program from executing normally as expected, which is the exception.
For example: the program needs to open a file and do some processing, but the file does not exist. The python code runs to the step of opening the file, because without this file, there is no way to open the file, and if there is no way to open the file, there is no way to process the file. This is an exception (a file opening exception).
The cause of the exception
Because some unexpected environments may occur when the program is running, the exceptions generated are different, for example, the file does not exist, there will be exceptions when opening the file, and there will also be exceptions caused by programmers' failure to comply with the specification when developing (for example, the divisor cannot be zero, zero exceptions will be reported when the divisor is zero, and array operations are out of bounds, and so on. These are common exceptions for beginners).
Did you find that the abnormality of python is similar to that of java? Yes, exception mechanisms exist in many programming languages, such as java,JavaScript,python, but they may be different in detail, such as the keyword used for exception catching in python is different from that in java, and python has some special features.
Python built-in exception type BaseException # Base class of all exceptions +-- SystemExit # interpreter requests exit +-- KeyboardInterrupt # user interrupts execution (usually input ^ C) +-- GeneratorExit # generator (generator) occurs exception to notify exit +-- Exception # base class of general exception +-- StopIteration # iterator has no more values +-- StopAsyncIteration # required The base class that must be thrown by the _ _ anext__ () method of the asynchronous iterator object to stop iterating +-- ArithmeticError # built-in exceptions caused by various arithmetic errors | +-- FloatingPointError # floating-point calculation error | +-- OverflowError # numeric operation result is too large to represent | +-- ZeroDivisionError # divided (or modulo) zero (all data) Type) +-- AssertionError # raises +-- AttributeError # attribute reference or assignment fails when assert statement fails +-- BufferError # raises +-- EOFError # when BufferError # fails to perform buffer-related operations +-- ImportError # when the input () function reaches the file end condition (EOF) without reading any data Failed to import module / object | +-- ModuleNotFoundError # cannot find the module or the base class of the exception thrown when the None +-LookupError # mapping or the key or index used on the sequence is invalid in sys.modules | +-IndexError # sequence does not have this index (index) | +-- KeyError # mapping does not have this key +-- MemoryError # memory overflow error (not fatal for Python interpreter) +-- NameError # undeclared / initialized object (no attributes) | +-- UnboundLocalError # accessing uninitialized local variables +-- OSError # operating system error EnvironmentError,IOError,WindowsError,socket.error,select.error and mmap.error have been merged into OSError The constructor may return a subclass | +-- BlockingIOError # operation sets the blocking object (e.g. Socket) to a non-blocking operation | +-- ChildProcessError # failed on the child process | +-ConnectionError # the base class of connection-related exceptions | | +-- BrokenPipeError # attempts to write to the pipe when the other end is closed or attempts to write to the Close write on socket | | +-ConnectionAbortedError # connection attempt is aborted by peer | | +-ConnectionRefusedError # connection attempt is rejected by peer | | +-ConnectionResetError # connection is reset by peer | +-FileExistsError # create an existing file or directory | +-FileNotFoundError # request No Existing file or directory | +-- InterruptedError # system call is interrupted by input signal | +-- IsADirectoryError # requests file operation on the directory (such as os.remove ()) | +-- NotADirectoryError # requests directory operation on something that is not a directory (such as os.listdir ()) | +-- PermissionError # try not having sufficient access Run the operation under limited circumstances | +-- ProcessLookupError # given process does not exist | +-- TimeoutError # system function times out at the system level +-- weak reference created by the ReferenceError # weakref.proxy () function attempts to access objects that have been garbage collected +-- RuntimeError # triggers when an error that does not belong to any other category is detected. | +-- NotImplementedError # in the user-defined base class The abstract method requires the derived class to override the method or the class under development indicates that the actual implementation still needs to be added | +-- RecursionError # interpreter detected that the maximum recursive depth was exceeded +-- SyntaxError # Python syntax error | +-- IndentationError # indentation error | +-- TabError # Tab and space mixing +-- SystemError # Interpreter found internal error +-- TypeError # operation or function applied to inappropriate type of object +-- ValueError # operation or function received a parameter of correct type but inappropriate value | +-UnicodeError # encoding or decoding error related to Unicode occurred | +-UnicodeDecodeError # Unicode decoding error | +-- UnicodeEncodeError # Unicode Encoding error | +-- UnicodeTranslateError # Unicode transcoding error +-- Base class of Warning # warning +-- DeprecationWarning # Base class of warning about deprecated features +-- PendingDeprecationWarning # Base class of warning about deprecated features +-- RuntimeWarning # about suspicious runtime behavior Base class for warnings +-- SyntaxWarning # about base classes for suspicious syntax warnings +-- UserWarning # base classes for user code generation warnings +-- FutureWarning # base classes for warnings about deprecated features +-- ImportWarning # Base classes for warnings about possible errors in module import +-- UnicodeWarning # are compared with Unicode Base class for off warnings +-- BytesWarning # Base class for warnings related to bytes and bytearray +-- ResourceWarning # Base class for warnings related to resource usage. Ignored by the default warning filter. Exception handling
In python, exceptions are caught in a different way than java. The statement he uses is, try-except-finally. The code is as follows:
Try: # attempted code that may throw an exception except exception type 1: # when an exception is thrown, execute the corresponding statement # except statement according to the type of exception to catch the exception. Except exception type 2: / / program code finally: # No matter what happens in the end, the statement that must be executed is generally done to clean up the type and so on. # finally is not necessary.
In addition, python provides a raise method to throw an exception message, as an example of the following code:
From random import randintnumber = randint (1 d is odd 9) if number%2==0: raise NameError ("% d is even"% number) # although it is judged that the odd and even numbers have nothing to do with NameError, the exception else: raise NameError ("% d is odd"% number) can still be thrown through raise
Raise can only use exception classes built into python.
Thank you for reading, the above is the content of "how python triggers and handles exceptions". After the study of this article, I believe you have a deeper understanding of how python triggers and handles exceptions, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.