SoFunction
Updated on 2024-11-10

python try exception handling (most complete ever)

In the program when there is a bug generally will not display the error message to the user, but the reality of a hint of the page, in layman's terms, is not to let the user see the rhubarb page!!!!

Sometimes when we write a program, there are errors or exceptions that cause the program to terminate .

To handle exceptions, we use try... .except

Put statements where errors may occur in the try module and use except to handle exceptions.

except can handle a specialized exception or a set of exceptions in parentheses.

If no exception is specified after except, all exceptions are handled by default.

For every try, there must be at least one except

Among python's exceptions, there is a catch-all exception: Exception, who can catch any exception

s1 = 'hello'
try:
  int(s1)
except Exception,e:
  print e

The program needs to take into account the possibility of multiple exceptions in the try block, which can be written like this:

s1 = 'hello'
try:
  int(s1)
except IndexError,e:
  print e
except KeyError,e:
  print e
except ValueError,e:
  print e

Simple and complex structures of exceptions

 try:
pass
except Exception as e: #python2 can also be written like this: except Exception,e
pass

full set of real columns

try:
  # Main code block
  pass
except KeyError,e:
  # Execute the block on an exception
  pass
else:
  # After the main code block is executed, execute the block
  pass
finally:
  # Finalize the execution of the block, regardless of exceptions
  pass

Define the special alert exception first, and then define the Exception to ensure that the program runs properly.

first the special, then the universal

s1 = 'hello'
try:
  int(s1)
except KeyError,e:
  print 'Key error'
except IndexError,e:
  print 'Indexing error'
except Exception, e:
  print 'Error'

active trigger exception

raise Exception('messages') can be customized.

a=2
if a > 1:
  raise ValueError('Value greater than 1')

raise Trigger Exception

try:
  raise Exception('Wrong...')
except Exception,e:
  print e

Customized exceptions

 class WupeiqiException(Exception):
 
  def __init__(self, msg):
     = msg
 
  def __str__(self):
    return 
 
try:
  raise WupeiqiException('My anomaly')
except WupeiqiException,e:
  print e

All of python's standard exception classes:

Exception Name descriptive
BaseException Base class for all exceptions
SystemExit Interpreter Request Exit
KeyboardInterrupt User interrupt execution (usually input ^C)
Exception Base Classes for Routine Errors
StopIteration The iterator has no more values
GeneratorExit The generator throws an exception to notify the exit.
SystemExit Python interpreter requests exit
StandardError Base class for all built-in standard exceptions
ArithmeticError Base class for all numerical computation errors
FloatingPointError floating point miscalculation
OverflowError Numerical operations exceeding the maximum limit
ZeroDivisionError Divide (or modulo) zero (all data types)
AssertionError Assertion statement failed
AttributeError The object does not have this property
EOFError No built-in inputs, EOF flag reached.
EnvironmentError Base class for operating system errors
IOError Input/output operation failed
OSError operating system error
WindowsError System call failure
ImportError Failed to import module/object
KeyboardInterrupt User interrupt execution (usually input ^C)
LookupError Base class for invalid data queries
IndexError There is no index in the sequence.
KeyError There is no such key in the mapping
MemoryError Memory overflow error (not fatal for Python interpreter)
NameError Undeclared/initialized object (no attributes)
UnboundLocalError Accessing uninitialized local variables
ReferenceError Weak reference tries to access an object that has already been garbage collected.
RuntimeError General Runtime Errors
NotImplementedError Methods not yet realized
SyntaxError Python Syntax Errors
IndentationError indentation error
TabError Mixing Tabs and Spaces
SystemError General Interpreter System Errors
TypeError Operations that are not valid for the type
ValueError Passing in invalid parameters
UnicodeError Unicode-related errors
UnicodeDecodeError Errors in Unicode Decoding
UnicodeEncodeError Unicode encoding error
UnicodeTranslateError Unicode conversion error
Warning Base class for warnings
DeprecationWarning Warning about discarded features
FutureWarning Warning about future semantic changes to constructs
OverflowWarning The old warning about automatic lifting to long integer (long)
PendingDeprecationWarning Warning that features will be deprecated
RuntimeWarning Warnings of suspicious runtime behavior
SyntaxWarning Warning of suspicious syntax
UserWarning User code generated warnings

This is the whole content of this article.