Python learning notes 7: errors and exceptions

In the process of programming and running, we always encounter all kinds of errors.
1. Some errors are syntax errors when writing programs. For example, there are fewer colons, unreasonable indentation and so on.
2. Some errors are caused by problems in programming. For example, we should have output integer results and output string. This kind of error is usually called bug, which must be fixed.
3. Some errors are caused by user input. For example, if you ask the user to input email address, you will get an empty string. This error can be handled accordingly by checking the user input.
4. There is another kind of error that can't be predicted during program operation. For example, when writing files, the disk is full and can't be written in, or the network suddenly breaks down after grabbing data from the network. This kind of error is also called exception, which must be handled in the program. Otherwise, the program will terminate and exit due to various problems.

Therefore, the program needs a mechanism to deal with errors and exceptions, and Python's error and exception handling ability is very powerful. It has many built-in exceptions, which can accurately feed back error information to users.
1. Syntax error

>>> if True print('hello world!') # Write less: colon
SyntaxError: invalid syntax

2.Python built-in exception
An exception is an event that occurs during program execution and affects the normal execution of the program.
In general, an exception occurs when Python cannot handle the program properly.
An exception is a Python object that represents an error.
When an exception occurs in a Python script, we need to capture and handle it, otherwise the program will terminate execution.

In Python, exceptions are also objects that can be manipulated. BaseException is the base class of all built-in exceptions, but user-defined classes do not directly inherit BaseException. All Exception classes inherit from Exception and are defined in exceptions module.
Python automatically puts all exception names in the built-in namespace, so the program can use exceptions without importing the exceptions module. Once a SystemExit exception is thrown and not caught, program execution is terminated. If the interactive session encounters an uncapped SystemExit exception, the session will terminate.

BaseException  # Base class for all exceptions
 +-- SystemExit  # Interpreter requests exit
 +-- KeyboardInterrupt  # User interrupts execution (usually by entering ^ C)
 +-- GeneratorExit  # An exception occurred in the generator to notify the exit
 +-- Exception  # Base class of general exception
      +-- StopIteration  # The iterator has no more values
      +-- StopAsyncIteration  # Must pass the of an asynchronous iterator object__ anext__ () method raised to stop iteration
      +-- ArithmeticError  # The base class of built-in exceptions caused by various arithmetic errors
      |    +-- FloatingPointError  # Floating point calculation error
      |    +-- OverflowError  # The numerical result is too large to represent
      |    +-- ZeroDivisionError  # Divide (or modulo) zero (all data types)
      +-- AssertionError  # Raised when the assert statement fails
      +-- AttributeError  # Property reference or assignment failed
      +-- BufferError  # Raised when a buffer related operation cannot be performed
      +-- EOFError  # Raised when the input() function reaches the end of file condition (EOF) without reading any data
      +-- ImportError  # Failed to import module / object
      |    +-- ModuleNotFoundError  # Unable to find module or in sys None found in modules
      +-- LookupError  # The base class of the exception that is thrown when the key or index used on the map or sequence is invalid
      |    +-- IndexError  # This index does not exist in the sequence
      |    +-- KeyError  # This key is not in the map
      +-- MemoryError  # Memory overflow error (not fatal for Python interpreter)
      +-- NameError  # Undeclared / initialized object (no properties)
      |    +-- UnboundLocalError  # Accessing uninitialized local variables
      +-- OSError  # Operating system error, EnvironmentError, IOError, WindowsError, socket error´╝îselect.error and MMAP Error has been incorporated into OSError, and the constructor may return subclasses
      |    +-- BlockingIOError  # Operation sets the blocking object (e.g. socket) to non blocking operation
      |    +-- ChildProcessError  # The operation on the child process failed
      |    +-- ConnectionError  # Base class for connection related exceptions
      |    |    +-- BrokenPipeError  # An attempt was made to write to a pipe when the other end was closed or to write on a socket that was closed for writing
      |    |    +-- ConnectionAbortedError  # The connection attempt was aborted by the peer
      |    |    +-- ConnectionRefusedError  # The connection attempt was rejected by the peer
      |    |    +-- ConnectionResetError    # Connection reset by peer
      |    +-- FileExistsError  # Create an existing file or directory
      |    +-- FileNotFoundError  # Request a file or directory that does not exist
      |    +-- InterruptedError  # System call interrupted by input signal
      |    +-- IsADirectoryError  # Request a file operation on the directory (for example, os.remove())
      |    +-- NotADirectoryError  # Request a directory operation on something that is not a directory (for example, os.listdir())
      |    +-- PermissionError  # An attempt was made to run the operation without sufficient access rights
      |    +-- ProcessLookupError  # The given process does not exist
      |    +-- TimeoutError  # The system function timed out at the system level
      +-- ReferenceError  # weakref. A weak reference created by the proxy () function attempts to access an object that has been garbage collected
      +-- RuntimeError  # Triggered 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  # The interpreter detected that the maximum recursion depth was exceeded
      +-- SyntaxError  # Python syntax error
      |    +-- IndentationError  # Indent error
      |         +-- TabError  # Mixed use of Tab and space
      +-- SystemError  # The interpreter found an internal error
      +-- TypeError  # An action or function is applied to an object of an inappropriate type
      +-- ValueError  # The operation or function received an argument with the correct type but an inappropriate value
      |    +-- UnicodeError  # A Unicode related encoding or decoding error has occurred
      |         +-- UnicodeDecodeError  # Unicode decoding error
      |         +-- UnicodeEncodeError  # Unicode encoding error
      |         +-- UnicodeTranslateError  # Unicode transcoding error
      +-- Warning  # Warning base class
           +-- DeprecationWarning  # Base class for warnings about deprecated features
           +-- PendingDeprecationWarning  # Base class for warnings about deprecated features
           +-- RuntimeWarning  # Base class for warnings about suspicious runtime behavior
           +-- SyntaxWarning  # Base class for suspicious syntax warnings
           +-- UserWarning  # Base class for user code generated warnings
           +-- FutureWarning  # Base class for warnings about deprecated features
           +-- ImportWarning  # Base class for warnings about possible errors in module import
           +-- UnicodeWarning  # Base class for Unicode related warnings
           +-- BytesWarning  # Base class for warnings related to bytes and byte array
           +-- ResourceWarning  # Base class for warnings related to resource usage. Ignored by default warning filter.

exception handling


    try_suite        #Logical code to process
except Exception[e]: #Exception is the exception class to handle, e used to save the type of exception
    exception_block  #Handling logic after catching exceptions

#Try is used to capture try_ The operation in suite, and the error is handed over to except for processing.
#Exception is used to handle exceptions. If the handling of exceptions is consistent with the setting of exceptions, exception is used_ Block handles exceptions. If they are inconsistent, they will be handled by the interpreter. If e is set, this error will be saved in E.

The following code:

except NameError as e:

print 'over'

#Output results
Error: name 'a' is not defined

The following exception can be caught because it is a runtime error:

    print("catch an except")

The exception cannot be caught because it is a syntax error and a pre run error (because the interpreter will check the syntax before the code runs and throw an error when the code is not actually running)

>>> try:
    if undef
    print("catch an except")
SyntaxError: invalid syntax

The following exceptions can be caught, and you can specify to handle an exception (NameError):

>>> try:
except NameError as e:
	print('catch an except {}'.format(e))

catch an except name 'undef' is not defined

The following code:
Output the result and report an error. The error is NameError: name 'undef' is not defined
The exception cannot be caught because setting IOError will not handle NameError and will throw the exception to the interpreter for processing

>>> try:
except IOError as e:
	print('catch an except {}'.format(e))

Traceback (most recent call last):
  File "<pyshell#41>", line 2, in <module>
NameError: name 'undef' is not defined

The else clause will be executed when no exception occurs in the try clause.

>>> try:
except Exception as e: #All exceptions are handled
	print('error come: {}'.format(e))
	print('no error') #If any exception occurs in the try clause, do not execute here

error come: name 'name' is not defined

>>> try:
except Exception as e:
	print('error come: {}'.format(e))
	print('no error') #There is no exception in the try clause. Execute here

no error

finally statement will execute the last code whether an exception occurs or not.

>>> try:
except Exception as e:
	print('error come: {}'.format(e))
	print('no error')
	print('finally come here') #The last code will be executed whether or not an exception occurs

error come: name 'name' is not defined
finally come here

Throw exception
Python uses the raise statement to throw a specified exception.

The format of raise syntax is as follows:

raise [Exception [, args [, traceback]]]

The following example triggers an exception if x is greater than 5:

>>> x=6
>>> if x>5:
	raise Exception('x cannot large than 5, x={}'.format(x))

Traceback (most recent call last):
  File "<pyshell#4>", line 2, in <module>
    raise Exception('x cannot large than 5, x={}'.format(x))
Exception: x cannot large than 5, x=6

Tags: Python

Posted by PJNEW on Sat, 07 May 2022 08:27:02 +0300