python3.7 Getting Started series of 12 anomalies

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/bowei026/article/details/90140229

Exception
the ZeroDivisionError
A. 5 =
B = 0
C = A / B
being given run:
the ZeroDivisionError: Division by ZERO

Catch exceptions try - except - else - finally statement
the try:
    A =. 3
    B = 0
    C = A / B
the except Exception AS E:
    Print ( "Exception:", E)
the else:
    Print ( "the else")
the finally:
    Print ( " finally ")
operating results:
Exception: ZERO Division by
a finally
which, except statement block is executed when an exception occurs, executes else is not an exception occurs, finally are no circumstances will any running
try statement is used to handle exceptions, to avoid in the case of abnormal crashes

FileNotFoundError
try:
    with open('d:/4.txt', 'r') as f:
        f.read()
except FileNotFoundError as e:
    print('Exception')

Some may be silent when an exception occurs, you must allow users or developers know when some abnormality occurs, it is necessary to write the corresponding code is processed according to the actual situation

json.dump json data is written to the file, json.load json data read from the file
Import json

= Fruits [ 'Apple', 'Banana', 'PEAR']
with Open ( 'D: /5.txt', 'W') AS F:
    The json.dump (Fruits, F)
to control programs, d: / 5 .txt files, open just to see if the content is written json data
import json

with open('d:/5.txt', 'r') as f:
    fruits = json.load(f)
    print(fruits)
运行结果:
['apple', 'banana', 'pear']

Thrown The raise
DEF divId (A, B):
    IF B == 0:
        The raise Exception ( 'dividend is not 0')

the try:
    divId (. 3, 0)
the except Exception AS E:
    Print (E)
result:
the dividend is not 0
catch the exceptions may be left untreated, continue to throw out
the try:
    divId (. 3, 0)
the except Exception AS E:
    raise e
run results:
Traceback (MOST Recent Last Call):
  File "E: \ tmp \ logs \ the main.py", Line. 8, in <Module1>
    raise e
  File "E: \ tmp \ logs \ the main.py", . 6 Line, in <Module1>
    divId (. 3, 0)
  File "E: \ tmp \ logs \ the main.py", Line. 3, in divId
    The raise Exception ( 'dividend is not 0')
Exception: dividend is not 0

Custom exception
inherit defined exception classes Excepton python own exception classes MyException
class MyException (Exception):
    DEF __init __ (Self, the Message):
        self.message the Message =

    def __str__(self):
        return str(self.message)


divId DEF (A, B):
    IF B == 0:
        The raise MyException ( 'dividend is not 0')

try:
    divid(3, 0)
except MyException as e:
    print(e)

The result:
the dividend can not be 0

This concludes this article, it may be more concerned about the number of public and personal micro signal:

Guess you like

Origin blog.csdn.net/bowei026/article/details/90140229