Python Foundation (21): exception handling

Time:2020-3-10

1. Exceptions and errors

1.1 mistake

There are two kinds of errors in the program

1.1.1 syntax error

Syntax error: this kind of error cannot pass the syntax detection of Python interpreter at all, and must be corrected before the program is executed.

#Demonstration 1 of grammatical errors
if

#Demonstration 2 of grammatical errors
def test:
    pass

#Demonstration 3 of grammatical errors
print(haha

1.1.2 logic error

#Incomplete user input (such as blank input) or illegal input (input is not a number)
num=input(">>: ")
int(num)

#Unable to complete calculation
res1=1/0
res2=1+'str'

1.2 what is abnormal

An exception is a signal of an error when the program is running. In Python, the exception triggered by an error is as follows:

1.3 types of abnormality

Different exceptions in Python can be identified by different types (classes and types are unified in Python, i.e. types). Different class objects identify different exceptions. An exception identifies an error.

1.3.1 exception example

1. Trigger indexerror:

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

2. Trigger keyerror

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

3. Trigger valueerror

s='hello'
int(s)

1.3.2 common exceptions

Attributeerror attempts to access a tree without an object, such as foo. X, but foo has no attribute x
Ioerror I / O exception; basically cannot open file
Importerror failed to import module or package; basically a path or name error
Indexerror syntax error (subclass of); code not properly aligned
Indexerror index index is beyond the sequence boundary. For example, when x has only three elements, it attempts to access x [5]
Keyerror trying to access a key that does not exist in the dictionary
Keyboardinterrupt Ctrl + C pressed
NameError uses a variable that has not been assigned to an object
Syntax error Python code is illegal, code cannot be compiled (I think it's a syntax error, wrong writing)
Typeerror the type of the incoming object does not match the expected
Unboundlocalerror attempts to access a local variable that has not been set, basically because there is another global variable with the same name,
That makes you think you're visiting it
Valueerror passes in a value that the caller does not expect, even if the value type is correct

1.3.3 more exceptions

ArithmeticError
AssertionError
AttributeError
BaseException
BufferError
BytesWarning
DeprecationWarning
EnvironmentError
EOFError
Exception
FloatingPointError
FutureWarning
GeneratorExit
ImportError
ImportWarning
IndentationError
IndexError
IOError
KeyboardInterrupt
KeyError
LookupError
MemoryError
NameError
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
ReferenceError
RuntimeError
RuntimeWarning
StandardError
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError

2. Exception handling

After an exception occurs, the code after the exception will not execute. If you want the code to run normally, you need to handle the exception.

2.1 what is exception handling

The Python interpreter detects an error and triggers an exception (which also allows the programmer to trigger the exception himself).

The programmer writes specific code to catch the exception (this code has nothing to do with program logic and exception handling).

If the capture is successful, you will enter another processing branch and execute the logic you customized for it, so that the program will not crash. This is called exception handling.

2.2 why exception handling

The python parser executes the program. When an error is detected, an exception is triggered. After the exception is triggered and is not handled, the program terminates at the current exception. The following code will not run. Who will use a software that runs and crashes suddenly.

So you have to provide an exception handling mechanism to enhance the robustness and fault tolerance of your program.

2.3 how to handle exceptions

First of all, exceptions are caused by program errors. Syntax errors have nothing to do with exception handling and must be fixed before the program runs.

Python causes a type for each exception, and then provides a specific syntax structure for exception handling.

2.3.1 basic grammar

Format:

try:
     Detected code block
Exception type:
     Once an exception is detected in try, the logic at this location is executed

Case study:

try:
    f = open('a.txt')
    g = (line.strip() for line in f)
    print(next(g))
    print(next(g))
    print(next(g))
    print(next(g))
    print(next(g))
except StopIteration:
    f.close()

'''
Next (g) will trigger iteration F. next (g) in turn can read a line of contents of the file. No matter how large the file a.txt is, there is only one line of contents in the memory at the same time.
Tip: G is based on file handle F, so f.close() can only be executed after next (g) throws an exception stopiteration
'''

Exception class intelligence is used to handle the specified exception. If the exception is not specified, it cannot be handled.

#No exception was caught, and the program reported an error directly
s1 = 'hello'
try:
    int(s1)
except IndexError as e:
    print e

2.3.2 multi branch

Format:

try:
     Detected code block
Exception type:
     Once an exception is detected in try, the logic at this location is executed
Exception type:
     Once an exception is detected in try, the logic at this location is executed
    ...
Exception type:
     Once an exception is detected in try, the logic at this location is executed

As long as the error reporting code from top to bottom finds a branch that matches the error reporting type, it will execute the code in this branch, and then directly exit the branch. If you can’t find a branch that can handle the same type of error reporting, you will continue to go down. If you don’t find one, you will report an error.

Case study:

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

2.3.3 universal abnormality

In Python exceptions, there is a universal exception: exception, which can catch any exception, that is:

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

You may say that since there are all-purpose exceptions, I’d better use the above form directly. Other exceptions can be ignored.

You are right, but there are two situations to see:

1. If the effect you want is to discard all exceptions or use the same code logic to handle them, only one exception is enough.

s1 = 'hello'
try:
    int(s1)
except Exception,e:
    'discard or execute other logic'
    print(e)

#If you use exception uniformly, you can catch all exceptions, but it means that you use the same logic to handle all exceptions (the logic here is the code block following the current expect)

2. If the effect you want is that we need to customize different processing logic for different exceptions, then we need to use multiple branches.

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)

2.3.4 other abnormal structures

Format:

try:
     Detected code block
Exception type:
     Once an exception is detected in try, the logic at this location is executed
    ...
Exception type:
     Once an exception is detected in try, the logic at this location is executed
else:
    If there is no exception in the code block in try, execute
finally:
    The module is executed whether it is abnormal or not, usually for cleaning

Case study:

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 ('execute me if there is no exception in the code block in 'try')
finally:
    Print ('the module will execute no matter whether it is abnormal or not, usually for cleaning work ')

2.3.5 active triggering exception

try:
    Raise typeerror ('type error ')
except Exception as e:
    print(e)

2.3.6 user defined exception

class EvaException(BaseException):
    def __init__(self,msg):
        self.msg=msg
    def __str__(self):
        return self.msg

try:
    Raise evaexception ('wrong type ')
except EvaException as e:
    print(e)

2.4 when to use exception handling

Some students think so. After learning exception handling, it’s so powerful. I want to add try… Except to every part of my program to think about whether it will have logical errors. That’s good.

Try… Except should be used as little as possible, because it is an exception handling logic attached to your program, which has nothing to do with your main work.
If you add too much of this kind of things, it will lead to poor readability of your code. Only when some exceptions are unpredictable, you should add try… Except. Other logic errors should be corrected as much as possible.

Exception inheritance:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StandardError
      |    +-- BufferError
      |    +-- ArithmeticError
      |    |    +-- FloatingPointError
      |    |    +-- OverflowError
      |    |    +-- ZeroDivisionError
      |    +-- AssertionError
      |    +-- AttributeError
      |    +-- EnvironmentError
      |    |    +-- IOError
      |    |    +-- OSError
      |    |         +-- WindowsError (Windows)
      |    |         +-- VMSError (VMS)
      |    +-- EOFError
      |    +-- ImportError
      |    +-- LookupError
      |    |    +-- IndexError
      |    |    +-- KeyError
      |    +-- MemoryError
      |    +-- NameError
      |    |    +-- UnboundLocalError
      |    +-- ReferenceError
      |    +-- RuntimeError
      |    |    +-- NotImplementedError
      |    +-- SyntaxError
      |    |    +-- IndentationError
      |    |         +-- TabError
      |    +-- SystemError
      |    +-- TypeError
      |    +-- ValueError
      |         +-- UnicodeError
      |              +-- UnicodeDecodeError
      |              +-- UnicodeEncodeError
      |              +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
       +-- ImportWarning
       +-- UnicodeWarning
       +-- BytesWarning