【Python之旅】第四篇(二):Python异常处理与异常捕捉

简介:

 在Python程序的执行过程中,难免会出现异常的情况,如果做的是跟用户交互的程序,当用户输入不可接受的内容时,在可预见的范围内,我们当然是希望可以给用户一些提示,而不是原来Python内置异常中的那些提示语句,毕竟那些语句只适合给程序员做调试参考,对用户并没有多大的价值。因此这就需要了解Python的常见异常了。

    当然,我们也可以制作自己的异常,当用户输入满足或不满足我们的需求时,就可以触发这些异常,以使我们写的程序更加人性化。


1.Python常见异常与演示

    Python常见异常可列举如下:

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

    对常见的异常,做如下的简单演示:

IOError:输入/输出异常

1
2
3
4
>>> f = file( 'myfile.txt' )
Traceback (most recent call last):
   File  "<stdin>" , line  1 in  <module>
IOError: [Errno  2 ] No such file or directory:  'myfile.txt'


ImportError:无法引入模块或包

1
2
3
4
>>>  import  xpleaf
Traceback (most recent call last):
   File  "<stdin>" , line  1 in  <module>
ImportError: No module named xpleaf


IndexError:下标索引超出序列边界

1
2
3
4
5
6
7
>>> a = range( 3 )
>>> a
[ 0 1 2 ]
>>> a[ 3 ]
Traceback (most recent call last):
   File  "<stdin>" , line  1 in  <module>
IndexError: list index out of range


KeyError:试图访问字典里不存在的键

1
2
3
4
5
>>> mydict={ 'name' : 'xpleaf' }
>>> mydict[ 'age' ]
Traceback (most recent call last):
   File  "<stdin>" , line  1 in  <module>
KeyError:  'age'


NameError:使用一个还未被赋予对象的变量

1
2
3
4
>>> print xpleaf
Traceback (most recent call last):
   File  "<stdin>" , line  1 in  <module>
NameError: name  'xpleaf'  is  not defined


IndentationError:语法错误(的子类) ;代码没有正确对齐

1
2
3
4
5
6
7
>>>  for  in  range( 3 ):
...   print i
...     print  'Error!'
   File  "<stdin>" , line  3
     print  'Error!'
     ^
IndentationError: unexpected indent


SyntaxError:Python代码非法,代码不能编译

1
2
3
4
5
6
7
8
9
10
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python Error.py 
   File  "Error.py" , line  3
     prin kd
           ^
SyntaxError: invalid syntax
>>>  for
   File  "<stdin>" , line  1
     for
       ^
SyntaxError: invalid syntax


KeyboardInterrupt:Ctrl+C被按下

1
2
3
4
5
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python test.py 
name:^CTraceback (most recent call last):
   File  "test.py" , line  2 in  <module>
     name = raw_input( 'name:' )
KeyboardInterrupt


EOFError:Ctrl+D被按下

1
2
3
4
5
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python EOF.py 
name:Traceback (most recent call last):
   File  "EOF.py" , line  2 in  <module>
     name = raw_input( 'name:' )
EOFError


UnboundLocalError:试图访问一个还未被设置的局部变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
程序代码如下:
name =  'xpleaf'
 
def sayYourName(mark):
         if  mark ==  1 :
                 name =  'yonghaoye'
         else :
                 print  'My name is:' ,name
 
sayYourName( 0 )
 
执行情况如下:
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python test.py 
My name  is :
Traceback (most recent call last):
   File  "test.py" , line  10 in  <module>
     sayYourName( 0 )
   File  "test.py" , line  8 in  sayYourName
     print  'My name is:' ,name
UnboundLocalError: local  var iable  'name'  referenced before assignment
 
注意:如果是sayYourName( 1 ),则不会出现问题,此时相当于在函数中定义了一个局部变量


AttributeError:试图访问一个对象没有的属性,比如myInst.foo,但是myInst没有属性foo

1
2
3
4
5
6
7
8
9
10
11
>>>  class  myClass():
...     pass
... 
>>> myInst = myClass()
>>> myInst.bar =  'spam'
>>> myInst.bar
'spam'
>>> myInst.foo
Traceback (most recent call last):
   File  "<stdin>" , line  1 in  <module>
AttributeError: myClass instance has no attribute  'foo'


ValueError:传入一个调用者不期望的值,即使值的类型是正确的

1
2
3
4
>>> f = file( 'myfile.txt' , 'io' )
Traceback (most recent call last):
   File  "<stdin>" , line  1 in  <module>
ValueError: mode string must begin  with  one of  'r' 'w' 'a'  or  'U' , not  'io'


TypeError:传入对象类型与要求的不符合

1
2
3
4
5
>>> num =  3
>>> str =  'name'  + num +  'age'
Traceback (most recent call last):
   File  "<stdin>" , line  1 in  <module>
TypeError: cannot concatenate  'str'  and  'int'  objects


2.Python异常捕捉

    知道了常见的Python异常,就有需要对这些异常进行捕捉了,主要是使用:try...except语句进行异常的捕捉。

    简单演示一个异常的捕捉,假设这里要捕捉的异常为IndexError:

1
2
3
4
5
6
7
8
9
10
11
代码如下:
try :
         a = [ 1 2 3 ]
         a[ 3 ]
except IndexError:
         print  '\033[32;1mIndexError!\033[0m'
         
执行情况如下:
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python test.py 
IndexError!
xpleaf@xpleaf-

    except后面可以只加一个异常,即只捕捉一个异常,当然也可以捕捉多个异常,只是需要捕捉特定异常并且输出相对应信息时,就不适合把异常都放在一块进行捕捉了,这里我们分别捕捉两个异常,看看情况如何:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
代码如下:
try :
         a = [ 1 2 3 ]
         a[ 3 ]
         mydict = { 'name' : 'xpleaf' }
         mydict[ 'age' ]
 
except KeyError:
         print  '\033[32;1mKeyError!\033[0m'
 
except IndexError:
         print  '\033[32;1mIndexError!\033[0m'
         
执行情况如下:
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python test.py 
IndexError!

    上面的代码中,显然list和dict都是有错误的,但执行程序时,只返回list的异常信息,这说明,try语句在执行时是顺序执行的,并非是循环执行,即捕捉到list的异常后,并不会继续执行下一个语句,只有等异常解除时才会继续往下执行。

    当然except后面可以不加任何异常类型,此时,将会捕捉任何前面没有捕捉到的异常,这适合于一些未可预见的异常情况,如上面的程序,list异常和dict异常是我们可预料的,但假如这时加入一个不可预料的异常时(假设),就需要使用except后面不加异常的方法了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
代码如下:
try :
         a = [ 1 2 3 ]
         print a[ 2 ]
         mydict = { 'name' : 'xpleaf' }
         print mydict[ 'name' ]
         print  'Name:' ,name    #显然会触发NameError
 
except KeyError:
         print  '\033[32;1mKeyError!\033[0m'
 
except IndexError:
         print  '\033[32;1mIndexError!\033[0m'
except:
         print  'Something is wrong!'
         
执行情况如下:
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python test.py 
3
xpleaf
Name: Something  is  wrong!


3.try语句的其它选项

    执行异常捕捉时,try语句除了有except关键字外,还有下面两个常用的关键字:

else:没有发现异常时会执行(一般可能在做测试时使用)

finally:无论是否发生异常,都会执行

    可做如下的测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
程序代码如下:
try :
         name = [ 'a' , 'b' , 'c' ]
         name[ 2 ]
         mydict = {}
except IndexError,err:
         print  '\033[32;1mIndexError!\033[0m' ,err
except KeyError:
         print  '\033[32;1mKeyError!\033[0m'
except:
         print  '\033[32;1mSomething is wrong!\033[0m'
else :
         print  'No Error!'
finally :
         print  'Going to exit...'
 
执行情况如下:
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python test.py 
No Error!
Going to exit...

    显然上面的程序也可以做其它语句的测试,功能已经很明显了,这里就不做说明了。


4.制作自己的异常

    虽然Python本身内置的异常已经很多,但有些时候我们需要实现自己的异常功能:即当用户输入不满足我们人为设定的内容时,就会触发原来我们已经手动定义的异常,以达到某种功能。这里我们就需要制作自己的异常,当然也需要使用raise关键字:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
代码如下:
class  XpleafException(Exception):    #这里Exception是关键字
         pass
 
try :
         name = raw_input( 'name:' ).strip()
         if  name !=  'xpleaf' :
                 raise XpleafException
except XpleafException:
         print  'No valid name sepecfied...'
         
执行情况如下:
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python test.py 
name:xpleaf  
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python test.py 
name:yonghaoye 
No valid name sepecfied...
相关文章
|
7月前
|
运维 监控 算法
时间序列异常检测:MSET-SPRT组合方法的原理和Python代码实现
MSET-SPRT是一种结合多元状态估计技术(MSET)与序贯概率比检验(SPRT)的混合框架,专为高维度、强关联数据流的异常检测设计。MSET通过历史数据建模估计系统预期状态,SPRT基于统计推断判定偏差显著性,二者协同实现精准高效的异常识别。本文以Python为例,展示其在模拟数据中的应用,证明其在工业监控、设备健康管理及网络安全等领域的可靠性与有效性。
885 13
时间序列异常检测:MSET-SPRT组合方法的原理和Python代码实现
|
5月前
|
人工智能 C# Python
处理python异常
本文介绍了Python中的异常处理机制,并实现了一个简单的异常装饰器。通过`try/except`语句捕获异常,结合`finally`子句完成清理工作。为进一步优化代码结构,文章提出了使用装饰器处理异常的方法,避免函数中大量冗长的异常处理语句。通过类封装异常装饰器,多个函数可共享异常处理逻辑,提升代码简洁性和可维护性。总结强调了装饰器在异常处理中的优势,使代码更加优雅高效。
133 27
|
6月前
|
Python
如何处理python的常见异常问题
在Python语言中,python异常处理机制主要依赖try、except、else、finally和raise五个关键字。本篇文章将为大家详细讲解一下如何处理python的常见异常问题。
|
8月前
|
人工智能 Shell 开发工具
[oeasy]python065python报错怎么办_try_试着来_except_发现异常
本文介绍了Python中处理异常的基本方法,重点讲解了`try`和`except`的用法。通过一个计算苹果重量的小程序示例,展示了如何捕获用户输入错误并进行处理。主要内容包括: 1. **回顾上次内容**:简要回顾了Shell环境、Python3游乐场和Vim编辑器的使用。 2. **编写程序**:编写了一个简单的程序来计算苹果的总重量,但发现由于输入类型问题导致结果错误。 3. **调试与修正**:通过调试发现输入函数返回的是字符串类型,需要将其转换为整数类型才能正确计算。
154 32
|
8月前
|
数据库 Python
[oeasy]python066_如何捕获多个异常_try_否则_else_exception
本文介绍了Python中`try...except...else`结构的使用方法。主要内容包括: 1. **回顾上次内容**:简要复习了`try`和`except`的基本用法,强调了异常处理的重要性。 2. **详细解释**: - `try`块用于尝试执行代码,一旦发现错误会立即终止并跳转到`except`块。 - `except`块用于捕获特定类型的异常,并进行相应的处理。 - `else`块在没有异常时执行,是可选的。 3. **示例代码**:通过具体例子展示了如何捕获不同类型的异常(如`ValueError`和`ZeroDivisionError`),并解释了异常处理
152 24
|
12月前
|
存储 索引 Python
Python生成器、装饰器、异常(2)
【10月更文挑战第16天】
152 1
Python生成器、装饰器、异常(2)
|
11月前
|
测试技术 开发者 Python
对于Python中的异常要如何处理,raise关键字你真的了解吗?一篇文章带你从头了解
`raise`关键字在Python中用于显式引发异常,允许开发者在检测到错误条件时中断程序流程,并通过异常处理机制(如try-except块)接管控制。`raise`后可跟异常类型、异常对象及错误信息,适用于验证输入、处理错误、自定义异常、重新引发异常及测试等场景。例如,`raise ValueError(&quot;Invalid input&quot;)`用于验证输入数据,若不符合预期则引发异常,确保数据准确并提供清晰错误信息。此外,通过自定义异常类,可以针对特定错误情况提供更具体的信息,增强代码的健壮性和可维护性。
|
11月前
|
Python
在Python中,`try...except`语句用于捕获和处理程序运行时的异常
在Python中,`try...except`语句用于捕获和处理程序运行时的异常
275 5
|
11月前
|
Python
在Python中,自定义函数可以抛出自定义异常
在Python中,自定义函数可以抛出自定义异常
221 5
|
11月前
|
存储 开发者 Python
自定义Python的异常
自定义Python的异常
179 5

推荐镜像

更多