python base (21): exception handling

Keywords: Python Attribute less Windows

1. Exceptions and Errors

1.1 Error

There are inevitably errors in the program, and there are two types of errors

1.1.1 Syntax Error

Syntax error: This kind of error can not pass the python interpreter's grammar detection at all and must be corrected before the program is executed.

#Syntax Error Example 1
if

#Grammar Error Example 2
def test:
    pass

#Grammatical Error Model Three
print(haha

1.1.2 Logical Error

#Incomplete user input(For example, the input is empty)Or the input is illegal(Input is not a number)
num=input(">>: ")
int(num)

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

1.2 What is an exception

Exceptions are signals that errors occur while the program is running. In python, errors trigger exceptions as follows:

1.3 Anomalies

Different exceptions in Python can be identified by different types (python unifies classes and types, types are classes), different class objects identify different exceptions, and 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 that an object does not have, such as foo.x, but foo does not have attribute x
 IOError input/output exception; basically unable to open file
 ImportError cannot introduce modules or packages; basically a path problem or a name error
 IndentationError syntax error (subclass); code not aligned correctly
 IndexError subscript index is out of sequence bounds, such as when x has only three elements and tries to access x[5]
KeyError attempts to access keys that do not exist in the dictionary
 KeyboardInterrupt Ctrl+C is pressed
 NameError uses a variable that has not been assigned to an object
 SyntaxError Python code is illegal and cannot be compiled (I personally think this is a syntax error and has been written incorrectly)
TypeError incoming object type does not meet requirements
 UnboundLocalError is trying to access a local variable that has not been set, basically because there is another global variable with the same name.
Cause 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

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 will not execute after the exception, and exception handling is necessary if you want the code to run properly.

2.1 What is exception handling

The python interpreter detects errors and triggers exceptions (which allow programmers to trigger exceptions themselves).

Programmers write specific code specifically designed to catch this exception (this code has nothing to do with program logic, but with exception handling).

If the catch succeeds, it enters another processing branch and executes the logic you customize for it so that the program does not crash, which is exception handling.

2.2 Why exception handling

When the python parser executes a program, it detects an error, triggers an exception, and when the exception is triggered and not handled, the program terminates at the current exception. The code behind it will not run. Who will use a software that runs with a sudden crash?

So you must 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. Grammatical errors are not related to exception handling and must be corrected 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:
     Code Block Detected
 Exceept except ion type:
     Once an exception is detected in the try, the logic for this location is executed

Case:

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,successively next(g)You can read a line of a file, regardless of the file a.txt How big is it? There is only one line in memory at a 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 specified exceptions, which cannot be handled if no exceptions are specified.

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

More than 2.3.2 branches

Format:

try:
     Code Block Detected
 Exceept except ion type:
     Once an exception is detected in the try, the logic for this location is executed
 Exceept except ion type:
     Once an exception is detected in the try, the logic for this location is executed
    ...
Exceept except ion type:
     Once an exception is detected in the try, the logic for this location is executed

Code that errs from top to bottom executes the code in that branch and exits the branch directly whenever a branch matches the type of error is found.If you can't find a branch that handles the same type of error, you'll keep going, and if you don't find one, you'll get an error.

Cases:

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

233,000 omnipotent anomalies

Among python's exceptions, there is one omnipotent exception: Exception, which can catch any exception, that is:

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

You might say that since there are omnipotent exceptions, I would just like to use the above form, other exceptions can be ignored.

You're right, but there are two things to look at:

1. If you want the effect that we discard all exceptions, or use the same piece of code logic to process them, then only one Exception is sufficient.

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

#If you use them all Exception,Yes, you can catch all exceptions, but that means you use the same logic to handle all exceptions (the logic here is the current one) expect Code block following)

2. If you want the effect that we need to customize different processing logic for different exceptions, you need to use more branching.

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 structures with abnormalities

Format:

try:
     Code Block Detected
 Exceept except ion type:
     Once an exception is detected in the try, the logic for this location is executed
    ...
Exceept except ion type:
     Once an exception is detected in the try, the logic for this location is executed
else:
    Execute code block without exception in try
finally:
    The module executes regardless of whether it is unusual or not, usually for cleanup

Case:

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('try Execute me if there are no exceptions in the inner code block')
finally:
    print('Abnormal or not,Will execute the module,Usually cleaning up')

2.3.5 Active Trigger Abnormality

try:
    raise TypeError('error in type')
except Exception as e:
    print(e)

2.3.6 Custom Exception

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

try:
    raise EvaException('error in type')
except EvaException as e:
    print(e)

2.4 When to use exception handling

Some students think so, after learning the exception handling, it's so strong that I want to add try...except to each of my programs to think about whether it will have logic errors. That's great.

try...except should be used as little as possible, because it is itself an exception handling logic that you attach to your program and has nothing to do with your main job.
More of this will cause your code to become less readable. try...except should be added only if some exceptions are unpredictable and other logic errors should be corrected as much as possible.

Exceptional 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

Posted by aviavi on Fri, 08 Nov 2019 21:43:42 -0800