python自定义异常

try             异常在try块里抛,如果会产生多个异常,捕捉第一个,匹配except,后边的不再捕捉

except: 抓异常

else:       try无异常,才会执行else

finally:   无论try块是否抛异常,永远执行的代码,通常用来执行关闭文件,断开服务器连接的功能

[[email protected] systeminformation]# vim ErrorExcept.py
#!/usr/bin/env python                                                                                                                                                              
#ecoding:utf-8                                                                                                                                                                     
                                                                                                                                                                                   
class FuncError(Exception):                                                                                                                                                        
    def __str__(self):                                                                                                                                                             
        return "I am func Error"                                                                                                                                                   
                                                                                                                                                                                   
def fun():                                                                                                                                                                         
    raise FuncError() #raise 抛出异常"I am func Error"                                                                                                                             
                                                                                                                                                                                   
try:                                                                                                                                                                               
    fun()                                                                                                                                                                          
except FuncError,e:                                                                                                                                                                
    print e                                                                                                                                                                        
                                                                                                                                                                                   
print ‘hello world‘   

[[email protected] systeminformation]# python ErrorExcept.py 
I am func Error
hello world
#!/usr/bin/env python                                                                                                                                                              
#ecoding:utf-8                                                                                                                                                                     

class FuncError(Exception):
    def __str__(self):
        return "I am func Error"

def fun():
    raise FuncError() #raise 抛出异常"I am func Error"

try:
   #fun()                                                                                                                                                           
    print  ‘a‘         #print ‘a‘正确显示结果,如果是print a,报错name error,打印!!                                                                                                                                           
except FuncError,e:    #如果print a 和fun()同时存在,print a在前,会打印!!,不打印I am fun error, fun()在前,打印I am fun error,不打印!!                                                                                                                                        
    print e                                                                                                                                                       
except NameError:                                                                                                                                                 
    print ‘!!‘                                                                                                                                                   
else:                  #不抛异常,输出a,这种情况下执行else内容                                                                                                                                         
    print ‘else‘                                                                                                                                                  
finally:               #finally无论如何都执行                                                                                                                                         
    print ‘finally‘
print ‘hello world‘    #print一定会执行

[[email protected] systeminformation]# python ErrorExcept.py                                                                                                                                
a
else
finally
hello world

#!/usr/bin/env python                                                                                                                                                              
#ecoding:utf-8                                                                                                                                                                     
                                                                                                                                                                                   
class FuncError(Exception):                                                                                                                                                        
    def __str__(self):                                                                                                                                                             
        return "I am func Error"                                                                                                                                                   
                                                                                                                                                                                   
def fun():                                                                                                                                                                         
    raise FuncError() #raise 抛出异常"I am func Error"                                                                                                                             
                                                                                                                                                                                   
try:                                                                                                                                                                               
   fun()               #即使有两个异常,抛出一个异常I am func Error,不再抛出第二个                                                                                                                                                                   
   print  a                                                                                                                                                                  
except Exception:       #匹配所有异常,匹配即结束,打印all exception                                                                                                                                                          
    print ‘all exception‘                                                                                                                                                          
except FuncError,e:                                                                                                                                                                
    print e                                                                                                                                                                        
except NameError:                                                                                                                                                                  
    print ‘!!‘                                                                                                                                                                     
else:                   #没有异常菜执行else,有异常不执行                                                                                                                                                       
    print ‘else‘                                                                                                                                                                   
finally:                                                                                                                                                                           
    print ‘finally‘                                                                                                                                                                
print ‘hello world‘  

[[email protected] systeminformation]# python ErrorExcept.py 
all exception
finally
hello world

glob:python下类似shell中的*的通配符

In [1]: import glob                                                                                                                                                                
                                                                                                                                                                                   
In [2]: glob.glob(‘/etc/*.conf‘)    #匹配/etc下*.conf文件,保存到list中                                                                                                                                              
Out[2]:                                                                                                                                                                            
[‘/etc/rsyslog.conf‘,
 ‘/etc/sensors3.conf‘,
 ‘/etc/GeoIP.conf‘,
 ‘/etc/Trolltech.conf‘,
 ‘/etc/nfsmount.conf‘,

shlex :分词模块,

[root[email protected] ~]# ps -eo pid,ppid,cmd                                                                                                                                            
  PID  PPID CMD
    1     0 /sbin/init
    2     0 [kthreadd]
    3     2 [migration/0]
    4     2 [ksoftirqd/0]

[[email protected] ~]# ipython
In [1]: import shlex                                                                                                                                                               
                                                                                                                                                                                   
In [2]: cmd = "ps -eo pid,ppid,cmd"                                                                                                                                                
                                                                                                                                                                                   
In [3]: shlex.split(cmd)              #返回列表元素                                                                                                                                              
Out[3]: [‘ps‘, ‘-eo‘, ‘pid,ppid,cmd‘]                                                                                                                                              

In [4]: import subprocess                                                                                                                                                          
                                                                                                                                                                                   
In [5]: subprocess.check_call(shlex.split(cmd))                                                                                                                                    
  PID  PPID CMD                                                                                                                                                                    
    1     0 /sbin/init                                                                                                                                                             
    2     0 [kthreadd]                                                                                                                                                             
    3     2 [migration/0]
时间: 2024-10-24 23:22:24

python自定义异常的相关文章

python自定义异常,使用raise引发异常

1.自定义异常类,自定义的异常类必须是Exception或者Error的子类! 1 #!/usr/bin/env python 2 # encoding: utf-8 3 4 class IllegalException(Exception): 5 ''' 6 Custom exception types 7 ''' 8 def __init__(self, parameter, para_value): 9 err = 'The parameter "{0}" is not lega

python自定义异常抛出接受多个数值

在使用Python的时候,有时候想自己自定义异常错误,同时抛出多个参数,比如对数据库查找一条数据,如果没有找到,返回 {"errCode":"-1", "errMsg":"该列数值是异常!"}的Json信息,那么异常需要抛出errCode和errMsg.下面的代码解决了该问题,也就是自定义异常抛出和接收多个值的技巧 运行之后获得的结果为: 注意这个自定义异常类需要继承ValueError类. 原文地址:https://www.

Python:自定义异常类

自定义一个异常类,判断用户输入的字符串长度是否够 #!/usr/bin/python #Filename:user_defined_exception.py class ShortInputException(Exception): '''A user-defined exception class.''' def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast

Python自定义异常及抛出异常

1 """ 2 自定义异常 3 """ 4 class MyException(Exception): # 继承异常类 5 def __init__(self, name, reason): 6 self.name = name 7 self.reason = reason 8 9 from datetime import datetime 10 try: 11 if str(datetime.now()) > "2018&quo

python自定义异常和主动抛出异常

#知识点:如何自定义类 class MyException(Exception): #让MyException类继承Exception def __init__(self,name,age): self.name = name self.age = age try: #知识点:主动抛出异常,就是实例化一个异常类 raise MyException("zhansgan",19) #实例化一个异常,实例化的时候需要传参数 except MyException as obj: #这里体现一个

Python 约束 , 自定义异常 , 加密 , 日志

约束 约束 , 约束其派生类:  保证派生类中必须编写send方法 , 不然执行可能就会报错 Python中  语法: 1 class BaseMessage(object): 2 def send(self): 3 """" 4 必须继承BaseMessage,然后其中必须编写send方法, 用于完成具体业务 5 """ 6 raise NotImplementedError(".send()必须被重新写") 7

python面向对象的约束和自定义异常

基于人为来约束: 即人为主动抛出异常 class BaseMessage(object): def send(self,x1): """ 必须继承BaseMessage,然后其中必须编写send方法.用于完成具体业务逻辑. """ raise NotImplementedError(".send() 必须被重写.") class Email(BaseMessage): def send(self,x1): "&quo

python 异常继承关系及自定义异常的实现

主要介绍 python 中异常的继承关系,及如何自定义异常 1. 异常的继承关系 BaseException # 所有异常的基类 +-- SystemExit # 解释器请求退出 +-- KeyboardInterrupt 用户中断执行(通常是输入^C) +-- GeneratorExit # 生成器(generator)发生异常来通知退出 +-- Exception # 常规异常的基类 +-- StopIteration # 迭代器没有更多的值 +-- StandardError # 标准错误

python通过自定义异常,提前退出方法

python退出的操作,搜索后都是return.exit()等 return:退出一个方法,并返回一个值 exit():退出python 想要实现的功能: 方法A中调用多个方法,方法B.方法C...,方法B有一个开关,是否结束方法A.如果标记结束就直接退出方法A,继续执行其他的方法. 总的过程如下: print("执行A之前的方法") def A(): B(isfinished="true") C() print("方法A结束了,但是这句还要执行"