異常處理&&丟擲異常
阿新 • • 發佈:2019-01-27
異常處理機制: try…..except…..finally…..
try:
# 需要捕獲異常的程式碼塊, 必須執行, 如果遇到異常, 調轉到excepct語句;
# 如果異常能被except後面的Error捕獲, 執行except語句的內容, 然後執行finally;
# 如果異常不能被except後面的Error捕獲, 直接執行finally;;
f = open('/etc/passwd')
# 10/0
# a
# f.close()
except ZeroDivisionError as e:
print e
\# 捕獲異常NameError
except NameError as e:
print e
finally:
# 必須會執行的語句;
f.close()
print "正在關閉檔案......"
print "hello"
實驗:
print 10/0
print '這時測試會不會內打印出來'
--->>這種情況遇到10/0後直接報錯,程式退出,不會執行第二條列印命令
Traceback (most recent call last):
File "/Python/root/day09.py", line 12, in <module>
print 10/0
ZeroDivisionError: integer division or modulo by zero
try機制
try:
print 10/0
except Exception as e:
print e
finally:
print '這時finally語句'
print '這時測試會不會內打印出來'
--->>
integer division or modulo by zero
這時finally語句
這時測試會不會內打印出來
對於前邊的資料庫程式設計可以這樣
import time
import MySQLdb as mysql
db = {
'user': 'root' ,
'passwd': 'redhat',
'host': 'localhost',
'port': 3306,
'charset': 'utf8',
'db': 'user',
}
class mMysql(object):
##database形式引數
def __init__(self, **database):
##建立資料庫的連線
self.user = database['user']
self.__passwd = database['passwd']
self.host = database['host']
self.__port = database['port']
self.charset = database['charset']
self.db = database['db']
self.conn = mysql.connect(user=self.user, passwd=self.__passwd,
host=self.host, port=self.__port,
db=self.db, charset=self.charset)
##建立遊標,給資料庫傳送sql語句
self.cur = self.conn.cursor()
print '[%s]:資料庫正在連結中...' % time.ctime()
def is_table_exist(self, table_name):
self.cur.execute('show tables;')
for name in self.cur.fetchall():
if name[0] == table_name:
return True
else:
return False
def select_table(self, table_name, num=1):
try:
self.cur.execute('select * from %s' %table_name)
for i in self.cur.fetchmany(num):
print i
except Exception:
print '%s不存在' % table_name
def create_table(self, table_name, **attr):
s = ''
try:
for k, v in attr.items():
s = s + k + ' ' + v + ','
s = s.rstrip(',')
sqli = 'create table %s(%s);' %(table_name, s)
print 'sqli語句:', sqli
self.cur.execute(sqli)
print '%s建立成功' %(table_name)
except Exception:
print '%s已經存在了' %(table_name)
def __del__(self):
self.cur.close()
self.conn.close()
print '[%s]:資料庫正在斷開...' %(time.time())
sql = mMysql(**db)
sql.create_table('userinfo2', user='varchar(10)', age='int')
# sql.__del__()
# sql.select_table('python',2)
丟擲異常raise 異常型別
class AgeError(IOError):
pass
age = raw_input('Age:')
if not 0<int(age)<=200:
# raise IOError("age: between 0~200")
# 丟擲自定義異常
raise AgeError("age: between 0~200")