当前位置: 移动技术网 > IT编程>脚本编程>Python > python 自定义异常和异常捕捉的方法

python 自定义异常和异常捕捉的方法

2018年11月08日  | 移动技术网IT编程  | 我要评论

红颜露水网址导航,goshare,二手房最新政策

异常捕捉:

try: 
 xxxxx1
 raise exception(“xxxxx2”) 
except (exception1,exception2,……): 
 xxxx3
else:
 xxxxx4
finally:
 xxxxxxx5

1.raise 语句可以自定义报错信息,如上。

2. raise后的语句是不会被执行了,因为已经抛出异常,控制流将会跳到异常捕捉模块。

3. except 语句可以一个except后带多个异常,也可以用多个语句捕捉多个异常,分别做不同处理。

4. except语句捕捉的异常如果没有发生,那么except里的语句块是不被执行的。而是执行else里的语句

5. 在上面语句中try/except/else/finally所出现的顺序必须是try–>except x–>except–>else–>finally,即所有的except必须在else和finally之前,else(如果有的话)必须在finally之前,而except x必须在except之前。否则会出现语法错误。

6.else和finally都是可选的.

7.在上面的完整语句中,else语句的存在必须以except x或者except语句为前提,如果在没有except语句的try block中使用else语句会引发语法错误。

异常参数输出:

try:
 testraise()
except preconditionsexception as e: #python3的写法,必须用as
 print (e)

自定义异常,只需自定义异常类继承父类exception。在自定义异常类中,重写父类init方法。

class databaseexception(exception):
 def __init__(self,err='数据库错误'):
  exception.__init__(self,err)

class preconditionsexception(databaseexception):
 def __init__(self,err='preconditionserr'):
  databaseexception.__init__(self,err)

def testraise():
 raise preconditionsexception()

try:
 testraise()
except preconditionsexception as e:
 print (e)

注意:preconditonsexception又是databaseexception的子类。

所以如果,raise preconditionexception的话,用两个异常类都可以捕捉。

但是, 如果是raise databaseexception, 用preconditonsexception是捕捉不到的。

以上这篇python 自定义异常和异常捕捉的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网