Python Exception
posted on 12 Jul 2008 20:19 by plynoi in Tech
ช่วงนี้ใช้ (Iron)Python ทำ tool โง่ๆ ไว้ใช้เองบ่อย พอดีต้องทำงานกับ File เยอะครับ อยากจะ Automate บางอย่างซะ เลยสนใจเกี่ยวกับ Exception ไว้หน่อย กันพัง ซึ่งก็ง่ายๆ (ถนัด catch มากกว่าวุ้ย)
try:
do somethinig
except Exception:
do something
ที่นี้หาวิธีให้มัน print Exception อยู่ตั้งนาน ... ในที่สุดก็เจอdo somethinig
except Exception:
do something
try:
fi_lines=open(sys.argv[1],'r').readlines()
except ArithmeticError,aerr:
print 'There is Arithmetic Exception occure',aerr
except Exception,ER:
print 'There is Exception occure',ER
อย่างที่เห็นข้างบนคือโค๊ดอ่าน file ธรรมดาๆ ซึ่งบนวินโดวส์ถ้าใส่ path ที่มีช่องว่างจะ error ส่วนวิธีการ print exception info ก็ง่ายๆ เอาตัวแปรสักอย่างไปรับหลัง catch (except) แล้วก็สั่ง print ดื้อๆ แบบนั่นแล จะเห็นว่ามี level แบบภาษาอื่นๆ ด้วยถ้าไม่เกี่ยวก็โยนออกมาเรื่อยๆ ผลจะเหรอfi_lines=open(sys.argv[1],'r').readlines()
except ArithmeticError,aerr:
print 'There is Arithmetic Exception occure',aerr
except Exception,ER:
print 'There is Exception occure',ER
python test.py C:\Program Files\Mozilla Firefox\install.text
There is Exception occure [Errno 2] No such file or directory: 'C:\\Program'
หรือ IronPython
ipy test.py C:\Program Files\Mozilla Firefox\install.text
There is Exception occure Could not find file 'C:\Program'.
สำหรับ list ของ Exception ที่มีอยู่แล้วก็ดูตาม docโลด
There is Exception occure [Errno 2] No such file or directory: 'C:\\Program'
หรือ IronPython
ipy test.py C:\Program Files\Mozilla Firefox\install.text
There is Exception occure Could not find file 'C:\Program'.
Tags: exception, ironpython, plynoi, programming, python, tech1 Comments






#1 By (^_^)/nana on 2008-07-15 14:52