python中的异常处理

什么是异常?

在程序运行过程中影响程序正常运行的内容,

为什么需要异常处理?

可以让你的程序更加健壮, 可以清晰的快速修复异常。

1). print(s)
NameError: name 's' is not defined

2). li = [1,2,3]
li[10]
IndexError: list index out of range

3). 10/0
ZeroDivisionError: division by zero

>>> d = dict(a=1, b=2)
>>> d
{'a': 1, 'b': 2}
>>> d['c']
Traceback (most recent call last):
File "", line 1, in 
KeyError: 'c'

4).d = dict(a=1, b=2)
d
{'a': 1, 'b': 2}
d['c']
KeyError: 'c'

5).
AttributeError: 'Student' object has no attribute 'scores'

# print(s)
class Student(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def echo(self):
        return  self.name

    def __str__(self):
        return  "Student(%s)" %(self.name)

s = Student('黎明', 30)
# print(s.scores)
# s.echo1()

# FileNotFoundError: [Errno 2] No such file or directory: '/tmp/aa'
with open('/tmp/aa') as f:
    print(f.read()[:10])

try…except… else…finally…

普通的异常处理:

import  time
try:
# 如果你觉得代码可能出现问题,那么放在try语句中,只执行一次;
    print(s)
    # print("hello")
except NameError as e:   # 对于异常进行一个重命名;记录了异常的详细信息;
    # 可能执行一次, 也可能不执行;
    print("名称错误")
    with open("except.log", 'w') as f:
        f.write(time.ctime() + ' ')
        f.write(str(e))
finally:
    # 无论是否出现异常, 肯定会执行一次,
    print("处理结束")

import  time
try:
    # 如果你觉得代码可能出现问题, 那么放在try语句中, 只执行一次;
    print('hello')
    with open('/etc/aa') as f:
        print(f.read()[:5])

    print("文件读取结束")
    li = [1, 2, 3, 4]   # try语句中一旦出现问题, 后面的语句(try里面的)不执行
    print(li[5])
    print(s)
    print("hello")
except (NameError, IndexError) as e:   # 对于异常进行一个重命名;记录了异常的详细信息;
    # 可能执行一次, 也可能不执行;
    # print("名称错误")
    with open("except.log", 'a+') as f:
        f.write(time.ctime() + ' ' + str(e) + '\n')
finally:
    # 无论是否出现异常, 肯定会执行一次,
    print("处理结束")

官方实例

# 1).
class B(Exception):
    pass
class C(B):
    pass
class D(C):
    pass
for cls in [B, C, D]:
    try:
        raise cls()
    except D:
        print("D")
    except C:
        print("C")
    except B:
        print("B")

# 2).
import sys
# /etc/passwd /etc/group
for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except OSError:
        print('cannot open', arg)
    else:
        # 如果try语句中没有产生任何异常和错误, 才执行的语句;
        print(arg, 'has', len(f.readlines()), 'lines')
        f.close()

抛出异常

age = int(input("Age:"))

# try....except...finally  ===== 捕获异常
# raise ======   抛出异常
class AgeError(Exception):
    pass

if age < 0 or age > 120:
    raise  AgeError
else:
    print(age)

python内置异常结构

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

你可能感兴趣的:(python)