python——面向对象(下)

异常简介

异常,即程序中出现的错误

open("a.txt")

此时文件不存在,在执行程序是将显示如下:

Traceback (most recent call last): File "test.py", line 1,

in <module> open("a.txt") FileNotFoundError: [Errno 2] No such file or directory: 'a.txt'

捕获异常

异常一旦发生,如果不加以处理,则程序中断。 如何能够提高程序的健壮性?对于一般可预测性的异常,我们一般可以事先预防 即就是当程序出现问题时,我们有预先的处理机制。

try except语句

try:  

    print("异常发生前")  

    open("a.txt")  

    print("异常发生后")

    except IOError:  

    print("捕捉到了异常")

把可能出现问题的代码,放在try中

把处理异常的代码,放在except中

except也可以一次性捕捉多个异常:

try:  

    print("异常发生前")  

    print(num)

    open("a.txt")  

   print("异常发生后")

   except (IOError,NameError):  

   print("捕捉到了异常")


 也可用as关键字将异常信息存储:

try:  

    print("异常发生前")  

    print(num)    

    open("a.txt")  

    print("异常发生后")

    except (IOError,NameError) as result:  

    print("捕捉到了异常")  print(result)

嫌麻烦也可一次性捕捉所有异常:

try: 

     print("异常发生前")
     print(num)  

    open("a.txt")  

    print("异常发生后")

    except Exception as result:  

    print("捕捉到了异常")  

    print(result)

else如果没发生异常则执行:

try:  

    print("异常发生前")  

    #print(num)  

    #open("a.txt")  

    print("异常发生后")

    except Exception as result:  

    print("捕捉到了异常")  

    print(result) else:  print("万幸")


 finally无论错误与否,都要执行:

try:  

     print("异常发生前")

     #print(num)  

     #open("a.txt")  

     print("异常发生后")

     except Exception as result:  

     print("捕捉到了异常")  

     print(result) finally:  

     print("必须执行!")

栗子一:

try:
	print num
	print("Before error")
	open("a.txt")
	print("After error")
except IOError,NameError) as e:
	print(e)
	print("Except run...")
else:
	print("Else run...")
finally:
	#无论错与否 都要执行
	#主要去关闭一些资源 close
	print("Finally run...")

异常的传递

   如果一个异常是在一个函数中产生的,例如函数A---->函数B---->函数C,
而异常是 在函数C中产生的,那么如果函数C中没有对这个异常进行处理,那么
这个异常会传递到 函数B中,如果函数B有异常处理那么就会按照函数B的处理
方式进行执行;如果函数B也 没有异常处理,那么这个异常会继续传递,
以此类推。。。如果所有的函数都没有处 理,那么此时就会进行异常的默认处理,
即通常见到的那样
   当调用test3函数时,在test1函数内部产生了异常,此异常被传递到test3
函数中完成了异常处理,而当异常处理完后,并没有返回到函数test1中进行执行,
而是在函数 test3中继续执行

栗子二:

def test1():
	print("1-1")
	print(num)
	print("1-2")
def test2():
	print("2-1")
	test1()
	print("2-2")
test2()
def test3()
    try:
    	print("3-1")
    	test1()
    	print("3-2")
    except Exception as e:
    	print(e)
    	print("3-3")
#角标越界异常
class IndexOutOfBoundExcption(Exception):
	def __init__(self,index,info):
		self.index=index
		self.info=info
	def __str__(self):
		return "IndexOutOfBoundExcption!Because of :%s"%(self.index)
def show(l,index):
	if index<0 or index>=len(l):
		raise l[index]
	print l[index]

l=[1,2,3]
try:
	show(1,-5)
except IndexOutOfBoundExcption as e:
	print(e)
	
#test2()
test3()

抛出自定义异常

可以用raise语句来引发一个异常。异常/错误对象必须有一个名字,且它们应是ErrorException类的子类

异常处理中抛出异常

栗子三:

'''
老师上课
老师
电脑
   开机
      蓝屏
      冒烟
   重启


'''
class Teacher:
    def __init__(self):
    	self.name=name
    	self.computer=computer
    def teach(self):
    	try:
            self.computer.start()
        except BlueScreenException as e:
        	self.computer.restart()
        except MaoYanException as e:
        	print(e)
    	print(self.name+"class begining!")
class Computer:
    def __init__(self,type):
    	self.type=type
    def start(self):
    	print("computer running...")

    	if type==1: #BlueScreen
            raise.type==1:
    	if type==2: #Maoyan
    	    raise MaoYanException()
    def restart(self):
        print("The computer is restart")
        print("The computer is running")	    
class BlueScreenException(Exception):
	def __str__(self):
		return "The computer is BlueScreen now!"
class MaoYan(Exception):
	def __str__(self):
		return "The computer is MaoYan now!"
class ClassNotContinueException(Exception):
	def __str__(self):
		return "go home now!"
com=Computer(0)
teacher=Teacher("teacher",com)
try:
	teacher.teach()
except ClassNotContinueException as e:
	print(e)
	printt("Go home")

teacher.teach()

模块介绍

C语言中如果要引用sqrt函数,必须用语句#include  <math.h>引入math.h这个头文件,否则是无法正常进行调用的。 那么在Python中,如果要引用一些其他的函数,该怎么处理呢?在Python中有一个概念叫做模块(module),这个和C语言中的头文件以及Java中的包 很类似,比如在Python中要调用sqrt函数,必须用import关键字引入math这个模块说的通俗点模块就好比是工具包,要想使用这个工具包中的工具(就好比函数),就需要导入这个模块。

import:

在Python中用关键字import来引入某个模块,比如要引用模块math,就可以在文件最开始的地方用import math来引入。

在调用math模块中的函数时,必须这样引用:

模块名.函数名

模块制作

定义自己的模块:

在Python中,每个Python文件都可以作为一个模块,模块的名字就是文件的名字。 比如有这样一个文件test.py,

在test.py中定义了函数add

test.py

def add(a,b):

    return a+b

调用自己的模块:

那么在其他文件中就可以先import test,然后通过test.add(a,b)来调用了,当然也可以通 过from test import add来引入

main.py

import test

result = test.add(11,22)

print(result)

给程序传参数

import sys

print(sys.argv)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值