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 อยู่ตั้งนาน ... ในที่สุดก็เจออึ้ง
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 แบบภาษาอื่นๆ ด้วยถ้าไม่เกี่ยวก็โยนออกมาเรื่อยๆ ผลจะเหรอ
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โลด

Comment



smilebig smileopen-mounthed smileconfused smilesad smileangry smiletonguequestionembarrassedsurprised smilewinkdouble winkcry

โอ่ย...นู๋ม่ายเข้าจาย ฮือ ฮือsad smile sad smile

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