Python exception handling # learn to ape


 

 

### What is abnormal?

> Very simple to understand, is not functioning properly, did not meet expectations.

> Exception is an event, and this abnormal event occurs during the operation of our programmers will affect our normal program execution.

Abnormalities in two ways:

    1. syntax error caused by an abnormal

    2. Logical errors caused by abnormalities

### How to handle exceptions?

1. If an error occurs is predictable, then you can use the process control preventive treatment

```python

# For example: two digital operations, one of which is not numbers, operators will be wrong. Then you can go to determine prevention

n2 = 3

if isinstance(n2,int):

    res = 10 + n2

    print(res)

```

2. If an error occurs unpredictable conditions, you can use try. . . except. . Processed when an error occurs

```python

'''grammar:

try:

    The exception error codes that may occur

except:

    If an exception occurs except proceeds to process block

'''

# Assumption that reads file does not exist, an error occurs, you can use two methods for processing,

# 1. Before the file can be read to determine whether the current file exists

# 2. You can also use try. . . except. . Processed when an error occurs

try:

    with open('./user.txt','r') as fp:

        res = fp.read()

    print(res)

except:

    print ( 'file does not exist')

print ( 'program to continue ...')

```

** Note: try. . except. . The process is carried out after the error occurred. And if there's a fundamental difference. **

### Try. . . except. . Detailed usage

```python

# Try. . except detailed usage

# 1. Use try. . except processing specified exception. If triggered a non-specified exception, you can not handle

try:

    s1 = 'hello'

    int (s1) # raises ValueError

except ValueError as e:

# Except IndexError as e: # If triggered a non-specified exception, you can not handle

    print (e)

# 2. Multi-branch processing exception class. Different exception will go except processing

s1 = 'hello'

try:

    # int(s1) # ValueError

    s1[5]    # IndexError

except IndexError as e:

    print('IndexError',e)

except KeyError as e:

    print('KeyError',e)

except ValueError as e:

    print('ValueError',e)

# 3. General exception classes Exception

s1 = 'world'

try:

    int(s1)

except Exception as e:

    print('Exception ===',e)

# 4 + multibranched general exception class exception class. After this throws an exception will follow to perform a corresponding order from the Exception class to bottom.

s1 = 'hello'

try:

    # int(s1) # ValueError

    s1[5]    # IndexError

except IndexError as e:

    print('IndexError',e)

except KeyError as e:

    print('KeyError',e)

except ValueError as e:

    print('ValueError',e)

except Exception as e:

    print('Exception',e)

# 5。 try...except...else...

s1 = 'hello'

try:

    str (S1)

except IndexError as e:

    print('IndexError',e)

except ValueError as e:

    print('ValueError',e)

except Exception as e:

    print('Exception',e)

else:

    print ( 'when the try block without raising an exception, execution')

# 6。try...except..else..finally

# Finally, whether or not an exception is thrown, it will be executed. Often used to perform some cleanup.

s1 = 'hello'

try:

    int(s1)

    print ( 'previous code if an exception is raised, the block will not continue ..')

except IndexError as e:

    print('IndexError',e)

except ValueError as e:

    print('ValueError',e)

except Exception as e:

    print('Exception',e)

else:

    print ( 'when the try block without raising an exception, execution')

finally:

    print ( 'regardless of whether an exception, this block of code will be executed')

print ( 'code if the above processing and performs abnormal, then code execution continues behind')

# 7. Use raise, take the initiative to throw an exception

try:

    # You can use the initiative to raise throws an exception, and the exception information set

    raise Exception ( 'error')

except Exception as e:

    print('Exception',e)

#8. assert assert

assert 1 == 1 # if the latter expression is correct, do nothing

assert 2 == 1 # If the errors behind the expression, directly thrown AssertionError

```

Custom exception handler class ###

> When an exception occurs, the abnormal information is written to the log.

##### traceback module back https://docs.python.org/3.7/library/traceback.html

##### logging module logs https://docs.python.org/3.7/library/logging.html

```python

# Log custom exception handling classes

class Myexception():

    def __init__(self):

        import traceback

        import logging

        The basic configuration # logging

        logging.basicConfig(

            filename = '. / error.log', # log storage files and directories

            format = '% (asctime) s% (levelname) s \ n% (message) s', # format stored in log format

            datefmt='%Y-%m-%d %H:%M:%S'

        )

        # Write log

        logging.error(traceback.format_exc())

# Class using a custom exception handler

try:

    int ( 'bb')

except:

    print ( 'here in exception handling')

    Myexception () # code block to call exception handling custom exception class

```

### standard exception classes

| Exception Name | Description |

| :-----------------------: | :------------------------------------------------: |

| BaseException | base class for all exceptions |

| SystemExit | interpreter requested to exit |

| KeyboardInterrupt | User Interrupt Executing (usually enter ^ C) |

| Exception | General error base class |

| StopIteration | iterator no more value |

| GeneratorExit | exceptions to withdraw the notification generator (generator) occurs |

| StandardError | all the built-in standard base class for exceptions |

| ArithmeticError | all base class numerical errors |

| FloatingPointError | floating-point calculation error |

| OverflowError | numerical operation exceeds the maximum limit |

| The ZeroDivisionError | addition (or modulus) of zero (all data types) |

| AssertionError | assertion failure |

| AttributeError | object does not have this property |

| EOFError | no built-in input, to reach the EOF marker |

| EnvironmentError | operating system error base class |

| IOError | input / output operations to fail |

| OSError | operating system error |

| WindowsError | system call fails |

| ImportError | import module / object failed |

| LookupError | base class for invalid data queries |

| IndexError | sequence without this index (index) |

| KeyError | map does not have this key |

| MemoryError | memory overflow error (for Python interpreter is not fatal) |

| NameError | undeclared / initialize objects (no attributes) |

| UnboundLocalError | access uninitialized local variable |

| ReferenceError | weak reference (Weak reference) attempts to access the object has been garbage collection |

| RuntimeError | generic runtime error |

| NotImplementedError | unrealized method |

| SyntaxError | Python syntax errors |

| IndentationError | indentation errors |

| TabError | Tab and spaces mix |

| SystemError | general explanation of system error |

| TypeError | invalid for the type of operation |

| ValueError | passed invalid parameters |

| UnicodeError | Unicode related errors |

| UnicodeDecodeError | when Unicode decoding error |

| UnicodeEncodeError | when Unicode encoding error |

| UnicodeTranslateError | when Unicode conversion error |

| Warning | Warning base class |

| DeprecationWarning | About deprecated feature warning |

| FutureWarning | About semantic structure of the future will change warning |

| OverflowWarning | old on automatically promoted to a long integer (long) Warning |

| PendingDeprecationWarning | About features will be abandoned warning |

| RuntimeWarning | suspicious runtime behavior (runtime behavior) warning |

| SyntaxWarning | suspicious of grammar warning |

| UserWarning | user code generated warning |

 

Mastery learning method, as will bend to overtake!

Learning to ape: the achievements of their own just a boutique!

Guess you like

Origin www.cnblogs.com/itxdl/p/12522577.html