Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python
Python
  1. วิธี Catch OSError Exception ใน Python

    OSError เป็น error class ของ os module raised เมื่อ os-specific function error ตัวอย่าง # foobar.py import os import sys try: for i in range(5): print(i, os.ttyname(i)) except Exception as e: print(e) print(sys.exc_type) รันบน Linux: $ python foobar.py 0 /dev/pts/0 1 /dev/pts/0

  2. วิธี Handle Python Exception ใน Threads

    ใช้ Queue ส่ง exception จาก worker thread ไป main thread ตัวอย่าง import sys import threading import time import Queue def thread(args1, stop_event, queue_obj): print(start thread) stop_event.wait(12) if not stop_event.is_set(): try: raise Exception(boom!) ex

  3. วิธี Rethrow Python Exception ด้วย Type ใหม่

    Python 3 รองรับ Exception Chaining ด้วย raise ... from ตัวอย่าง try: 1/0 except ZeroDivisionError as e: raise ValueError(Sweet n Sour grapes) from e ผลลัพธ์ Python 3 Traceback (most recent call last): File ..., line 2, in 1/0 ZeroDivisionError: division by zero The above exception wa

  4. วิธี Handle Invalid Arguments ด้วย Argparse ใน Python

    Argparse จัดการ invalid arguments เองโดย default (exit พร้อม usage message) ตัวอย่าง # foo.py import argparse class InvalidArgError(Exception): pass parser = argparse.ArgumentParser() parser.add_argument(echo) args = parser.parse_args() try: print(args.echo) raise InvalidArgError exce

  5. วิธีเขียน Try/Except Catch ทุก Python Exceptions

    Rule of thumb: ไม่ควร catch ทุกอย่าง (bare except) เพราะจะจับ KeyboardInterrupt, SystemExit ด้วย ไม่แนะนำ try: # do_something() except: print(Exception Caught!) แนะนำ: Catch specific exceptions + bare except พร้อม re-raise try: f = open(file.txt) s = f.readline() i = int(s.strip(

  6. วิธี Catch Thread Exception ใน Caller Thread Python

    Thread con รันใน context แยกกัน Exception ไม่ propagate กลับ caller ต้องส่งผ่าน Queue ตัวอย่างโค้ด import sys import threading import Queue class ExcThread(threading.Thread): def __init__(self, foo): threading.Thread.__init__(self) self.foo = foo def run(self):

  7. วิธี Catch Exception ขณะใช้ Python With Statement

    ห่อ with statement ไว้ใน try-except ตัวอย่าง try: with open(myFile.txt) as f: print(f.readlines()) except: print(No such file or directory) ผลลัพธ์ No such file or directory with statement จะ close file อัตโนมัติ แม้มี exception

  8. วิธี Handle Python Exceptions ให้สะอาด (Cleaner)

    1. ใช้ finally สำหรับ cleanup เสมอ try: # some code except: handle_exception() finally: do_cleanup() 2. Cleanup เฉพาะตอนมี exception should_cleanup = True try: # some code should_cleanup = False except: handle_exception() finally: if should_cleanup: do_cleanup()

  9. Python Exceptions ทั้งหมดเป็น Runtime Errors หรือไม่

    ไม่ใช่ทั้งหมด บางอย่างเป็น Syntax Errors ตัวอย่าง Syntax Error if True print(hello) else: print(world) ผลลัพธ์ SyntaxError: invalid syntax การจัดกลุ่ม Errors Syntax errors - พบตอน parse โปรแกรม ยังไม่รัน Runtime errors - พบตอน execute (ZeroDivisionError, TypeError, etc.) Logical errors - โป

  10. วิธี Implement Custom Python Exception พร้อม Custom Message

    สร้าง class สืบทอดจาก Exception หรือ subclass ที่เฉพาะเจาะจง ตัวอย่าง class CustomValueError(ValueError): def __init__(self, arg): self.arg = arg try: a = int(input(Enter a number: )) if not 1 < a < 10: raise CustomValueError(Value must be within 1 and 10.) except Custom

  11. วิธี Pass Arguments by Reference ใน Python Function

    Python ใช้ Call by Object Reference ตัวแปรที่เป็น mutable object (list, dict) จะส่ง reference ไป ตัวอย่าง def modify(lst): lst.append(99) a = [1, 2] modify(a) print(a) # [1, 2, 99] - ค่าเปลี่ยนไป แต่ immutable objects (int, str, tuple) จะสร้าง object ใหม่ ไม่ส่งผลกลับ def modify(x): x = 10

Total 9001 -คอมพิวเตอร์  FirstPage PreviousPage NextPage LastPage CurrentPage:9/451  20-คอมพิวเตอร์/Page Goto:1 3 4 5 6 7 8 9 10 11 12 13 14 15