python基础之异常处理

为了增加编程的友好性,避免程序出现BUG时将错误信息显示给用户,有了异常处理这个好东东.

基础异常

while True:
    num1=input('num1:')
    num2=input('num2:')
    try:
        num1=int(num1)
        num2=int(num2)
    except Exception as ex:
        print(ex)

python中的异常非常多,每个异常专门处理某一项的异常:

AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
IOError 输入/输出异常;基本上是无法打开文件
ImportError 无法引入模块或包;基本上是路径问题或名称错误
IndentationError 语法错误(的子类) ;代码没有正确对齐
IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
KeyError 试图访问字典里不存在的键
KeyboardInterrupt Ctrl+C被按下
NameError 使用一个还未被赋予对象的变量
SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
TypeError 传入对象类型与要求的不符合
UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,
导致你以为正在访问它
ValueError 传入一个调用者不期望的值,即使值的类型是正确的

more:

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
a=[1,2,3,4]

try:
	 #print(b)  #如果添加此项,直接报错,IndexError不拦截
    a[40]
except IndexError as ex:
    print(ex)

out:

list index out of range

万能异常

在上面的异常中,不能处理其他功能的异常,于是就引出了一个万能的异常Exception,他可以捕获任意异常,就是此篇刚开始的程序里的东东.

那么问题来了,既然有了这个万能异常,那其他的能否忽略呢?答案是当然不能了,对于特殊处理或提醒的异常需要先定义,最后定义Exception来确保程序正常运行.

s1 = 'hello'
try:
    int(s1)
except KeyError as e:
    print '键错误'
except IndexError as e:
    print '索引错误'
except Exception as e:
    print '错误'

因为代码是从上到下执行的,所以为了避免Exception拦截,需要把

异常中的其他结构

try:
    pass	#主代码块
except Exception as ex:		#异常代码块
    pass
else:		#正常代码块
    pass
finally:	#不管正确与否,都执行此代码块
    pass

执行顺序为执行try,正确执行else,然后finally;执行try,错误执行except,然后finally.

主动触发异常

try:
    raise Exception('error!!')
except Exception as ex:
    print(ex)

自定义异常

class cc(Exception):
    def __init__(self,message):
        self.message=message

    def __str__(self):
        return self.message

try:
    raise cc('hello,world!!')
except cc as ex:
    print(ex)

out:

hello,world!!

断言

assert 1 == 2
assert 1 == 1

out:

Traceback (most recent call last):
  File "/Users/shane/PycharmProjects/Py_study/Base/test/page.py", line 89, in <module>
    assert 1 == 2
AssertionError

如果报错,会有AssertionError报错.

一个判断数字是否质数的程序:

def isPrime(n):
    """This function return a number is a prime or not"""
    assert n >= 2
    from math import sqrt
    for i in range(2, int(sqrt(n))+1):
        if n % i == 0:
            return False
    return True

res=isPrime(22)
print(res)
原文地址:https://www.cnblogs.com/ccorz/p/5624133.html