美文网首页
Python 异常 2018-08-01

Python 异常 2018-08-01

作者: 默写年华Antifragile | 来源:发表于2018-08-01 20:52 被阅读6次
  1. 例程:使用except并加上异常类型
# -*- coding: UTF-8 -*-                                          
try:
    fh = open("a.txt",'w')
    fh.write("This is a file for Exception test!")
except IOError:
    print "Error, file not found or access failure!"
else:
    print "Successful!"

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
Successful!
helloworld@LG-virtual-machine:~/code$ cat a.txt 
This is a file for Exception test!helloworld@LG-virtu
  • 通过打开a.txt也能看到write()是不加换行符的
    1.2. 为了测试,我们先把a.txt得写权限给去掉,再重新执行以上代码,可以发现无法写入而产生的异常
chmod -w a.txt
helloworld@LG-virtual-machine:~/code$ python test.py 
Error, file not found or access failure!
  1. 使用异常而不带任何异常类型
try:
    正常的操作
   ......................
except:
    发生异常,执行这块代码
   ......................
else:
    如果没有异常执行这块代码
  1. 使用异常而带多种异常类型
try:
    正常的操作
   ......................
except(Exception1[, Exception2[,...ExceptionN]]]):
   发生以上多个异常中的一个,执行这块代码
   ......................
else:
    如果没有异常执行这块代码
  1. try...finally语句:无论是否发生异常都将执行最后的代码
# -*- coding: UTF-8 -*-                                          
try:
    fh = open("a.txt",'w')
    fh.write("This is a file for Exception test!")
finally:
    print "Error: File not found or access error"

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
Error: File not found or access error
Traceback (most recent call last):
  File "test.py", line 3, in <module>
    fh = open("a.txt",'w')
IOError: [Errno 13] Permission denied: 'a.txt'

helloworld@LG-virtual-machine:~/code$ chmod +w a.txt 
helloworld@LG-virtual-machine:~/code$ python test.py 
Error: File not found or access error
  1. 异常的参数:一个异常可以带上参数,可以作为输出时的异常参数
try:
    正常的操作
   ......................
except ExceptionType, Argument:
    你可以在这输出 Argument 的值...

实例:

# -*- coding: UTF-8 -*-                                          
def temp_convert(var):
    try:
        return int(var)
    except ValueError,Arg:
        print "参数不包含数字:",Arg

print temp_convert('xyz')

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
参数不包含数字: invalid literal for int() with base 10: 'xyz'
None
  1. 触发异常:

raise [Exception [, args [, traceback]]]
语句中 Exception 是异常的类型(例如,NameError)参数标准异常中任一种,args 是自已提供的异常参数。

# -*- coding: UTF-8 -*-
def mye(level):
    if level < 1:
        raise Exception,"Invalid Error!" #触发异常后,后面的代码>将不会被执行

try:
    mye(0)
except Exception,err:
    print 1,err
else:
    print 2       

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
1 Invalid Error!
  1. 用户自定义的异常
    通过创建一个新的异常类,程序可以命名它们自己的异常。异常应该是典型的继承自Exception类,通过直接或间接的方式。
  • 以下为与RuntimeError相关的实例,实例中创建了一个类,基类为RuntimeError,用于在异常触发时输出更多的信息;
  • 在try语句块中,用户自定义的异常后执行except块语句,变量 e 是用于创建Networkerror类的实例。
# -*- coding: UTF-8 -*-
class NetworkError(RuntimeError):
    def __init__(self, arg):
        self.args = arg

try:
    raise NetworkError("Bad hostName")
except NetworkError,e:
    print e.args      

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
('B', 'a', 'd', ' ', 'h', 'o', 's', 't', 'N', 'a', 'm', 'e')

问题:为什么输出一个一个字母?以后再答

相关文章

  • Python 异常 2018-08-01

    例程:使用except并加上异常类型 输出: 通过打开a.txt也能看到write()是不加换行符的1.2. 为了...

  • 24:python中的异常

    异常: 首先看看python的异常继承树 python的异常分为两种. 1、内建异常:就是python自己定义的异...

  • Python异常处理

    参考 Python菜鸟教程错误与异常 Python 异常处理 错误和异常 Python中(至少)有两种错误:语法错...

  • Python学习(八)

    异常处理 Python中的异常类型总结: Python内置异常类的层次结构: 异常检测 try-except语句 ...

  • (三)python错误与异常&面向对象编程

    python错误与异常 语法错误与定位 异常捕获、异常处理 try:xxxexcept: 自定义异常 python...

  • Python错误处理机制

    @(python程序员)[Python] Python Cookbook 捕获所有的异常 处理异常的时候最好还会尽...

  • Python异常处理

    Python中文件的操作 Python异常的处理 异常的引发 try⋯finally的使用

  • Python常见异常

    python标准异常 异常名称 描述 BaseException 所有异常的基...

  • Python 异常

    Python 含有异常处理机制来帮助用户处理可能发生的错误异常。 1. 异常概念 异常是指Python程序运行过程...

  • 异常处理

    捕获异常 raise语法: 格式:raise 异常名称(‘异常描述’) python中常见的异常

网友评论

      本文标题:Python 异常 2018-08-01

      本文链接:https://www.haomeiwen.com/subject/foorvftx.html