SoFunction
Updated on 2024-10-30

Exception Handling in Python Explained

I. What is an anomaly

In python, the error triggers the following exception

II. Types of anomalies

In python different exceptions can be identified with different types, one exception identifies one kind of error.

1, commonly used exception class

  • AttributeError Trying to access a tree that an object doesn't have, e.g., but foo doesn't have the attribute x
  • IOError Input/output exception; basically, can't open a file
  • ImportError Unable to import module or package; basically a path problem or wrong name.
  • IndentationError Syntax error (subclass); code not properly aligned
  • IndexError subscript index out of sequence bounds, e.g. trying to access x[5] when x has only three elements
  • KeyError Trying to access a key that does not exist in the dictionary.
  • KeyboardInterrupt Ctrl+C is pressed.
  • NameError uses a variable that has not yet been assigned to an object
  • SyntaxError Python code is illegal, code won't compile (personally, I think it's a syntax error, misspelled)
  • TypeError The incoming object type does not match the requested one.
  • UnboundLocalError tries to access a local variable that hasn't been set yet, basically because there's another global variable with the same name that's causing you to think you're accessing it
  • ValueError passes in a value that the caller does not expect, even if the value is of the correct type.

2. Examples of anomalies:

# TypeError:int type not iterable
for i in 3:
    pass

# ValueError
num=input(">>: ") # Type hello
int(num)

# NameError
aaa

# IndexError
l=['egon','aa']
l[3]

# KeyError
dic={'name':'egon'}
dic['age']

# AttributeError
class Foo:pass


# ZeroDivisionError:Could not complete the calculation
res1=1/0
res2=1+'str'

III. Exception handling

1、Basic syntax try... . except

try:
    Detected Code Blocks
except Type of Exception:
    tryOnce an anomaly is detected in the,Just execute the logic for this position

give an example

try:
    f = [ 'a', 'a', 'a','a','a', 'a','a',]
    g = (() for line in f) # Tuple derivatives
    print(next(g))
    print(next(g))
    print(next(g))
    print(next(g))
    print(next(g))
except StopIteration:
    ()

The exception class can only be used to handle specified exceptions, if non-specified exceptions cannot be handled.

s1 = 'hello'
try:
    int(s1)
except IndexError as e:  # Exception not caught, program reports error directly
    print(e)

2、Multi-branch exception except...except and universal exception: Exception

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

3、try/except...else

The try/except statement also has an optional else clause, which, if used, must come after all except clauses.

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

for arg in [1:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print('cannot open', arg)
    else:
        print(arg, 'has', len(()), 'lines')
        ()

4, the final execution of the exception finally

The try-finally statement executes the final code regardless of whether an exception occurs.

Define cleanup behavior:

s1 = 'hello'
try:
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)
#except Exception as e:
#    print(e)
else:
    print('Code blocks within a try execute me if there are no exceptions')
finally:
    print('The module is executed regardless of the exception, usually for cleanup')

#invalid literal for int() with base 10: 'hello'

# The module is executed regardless of the exception, usually for cleanup

IV. Throwing an exception raise

Python uses the raise statement to throw a specified exception.

The raise syntax is formatted as follows:

raise [Exception [, args [, traceback]]]
try:
    raise TypeError('Exception thrown, type error')
except Exception as e:
    print(e)

The only argument to raise specifies the exception to be thrown. It must be an instance of an exception or a class of an exception (i.e., a subclass of Exception).

If you just want to know if this throws an exception and don't want to deal with it, a simple raise statement will throw it again.

try:
        raise NameError('HiThere')
    except NameError:
        print('An exception flew by!')
        raise
   
#An exception flew by!
#Traceback (most recent call last):
#  File "", line 2, in ?
#NameError: HiThere

V. Customized exceptions

You can have your own exceptions by creating a new exception class. The exception class inherits from the Exception class, either directly or indirectly, for example.

In this example, the default __init__() for class Exception is overridden.

class EgonException(Exception):
    def __init__(self, msg):
         = msg

    def __str__(self):
        return 


try:
    raise EgonException('Exception thrown, type error')
except EgonException as e:
    print(e) 

#throw an exception,type error

Basic Exception Class

When creating a module that is likely to throw a number of different exceptions, a common practice is to create a base exception class for the package, and then create different subclasses for different error cases based on that base class:.

Most exceptions end in "Error", just like standard exception naming.

class Error(Exception):
    """Base class for exceptions in this module."""
    pass
 
class InputError(Error):
    """Exception raised for errors in the input.
 
    Attributes:
        expression -- input expression in which the error occurred
        message -- explanation of the error
    """
 
    def __init__(self, expression, message):
         = expression
         = message
 
class TransitionError(Error):
    """Raised when an operation attempts a state transition that's not
    allowed.
 
    Attributes:
        previous -- state at beginning of transition
        next -- attempted new state
        message -- explanation of why the specific transition is not allowed
    """
 
    def __init__(self, previous, next, message):
         = previous
         = next
         = message

VI. Assertion of assert

assert is used to determine an expression and trigger an exception if the expression condition is false.

Assertions can return an error directly if the condition is not met for the program to run, rather than having to wait for the program to run and then crash.

The syntax is formatted as follows:

assert expression

Equivalent:

if not expression:
    raise AssertionError

assert can also be immediately followed by an argument: the

assert expression [, arguments]

Equivalent:

if not expression:
    raise AssertionError(arguments)

The following example determines whether the current system is Linux or not, and if the condition is not met, an exception is triggered directly without executing the next code:

import sys
assert ('linux' in ), "This code can only be executed under Linux."
# The next code to execute

# Traceback (most recent call last):
#    File "C:/PycharmProjects/untitled/", line 2, in 
# assert ('linux' in ), "This code can only be executed under Linux"
#  AssertionError: This code can only be used in the Linux under implementation

This is the end of this article on Python exception handling. I hope it will be helpful for your learning and I hope you will support me more.