Error Handling
Error handling: try/except แทน try/catch
หัวข้อที่มีชื่อว่า “Error handling: try/except แทน try/catch”การจัดการ error ของ Python แมปเข้ากับ try/catch/finally ของ TypeScript โดยตรง — พร้อมส่วนเสริมที่ทรงพลังหนึ่งอย่าง: ประโยค else ที่จะทำงานก็ต่อเมื่อ ไม่มี exception ถูก raise คีย์เวิร์ดคือ try/except/else/finally และคุณใช้ raise เพื่อโยน exception แทน throw
try / except พื้นฐาน
หัวข้อที่มีชื่อว่า “try / except พื้นฐาน”// TypeScriptfunction divide(a: number, b: number): number { if (b === 0) throw new Error("Cannot divide by zero"); return a / b;}
try { const result = divide(10, 2); console.log(`Result: ${result}`);} catch (err) { if (err instanceof Error) { console.error(`Error: ${err.message}`); }} finally { console.log("Always runs");}# Pythondef divide(a: float, b: float) -> float: if b == 0: raise ValueError("Cannot divide by zero") return a / b
try: result = divide(10, 2) print(f"Result: {result}")except ValueError as e: print(f"Error: {e}")finally: print("Always runs")ความต่างสำคัญ:
- ใช้
exceptแทนcatch - ใช้
raiseแทนthrow - คุณจับ exception type ที่เฉพาะเจาะจง โดยตรง (เช่น
except ValueError) ไม่ใช่ค่าทั่วไป - syntax
as eผูก exception object เข้ากับตัวแปร
exception หลายชนิด
หัวข้อที่มีชื่อว่า “exception หลายชนิด”// TypeScripttry { const data = JSON.parse("{ bad json }"); const num = parseInt("abc", 10); if (isNaN(num)) throw new RangeError("NaN");} catch (err) { if (err instanceof SyntaxError) { console.error("JSON error:", err.message); } else if (err instanceof RangeError) { console.error("Range error:", err.message); } else { throw err; // re-raise unknown errors }}# Python — multiple except clausesimport json
try: data = json.loads("{ bad json }") value = int("abc")except json.JSONDecodeError as e: print(f"JSON error: {e}")except ValueError as e: print(f"Value error: {e}")except Exception as e: raise # re-raise any other exception
# You can also catch multiple types in one clause:# except (ValueError, TypeError) as e:# print(f"Either error: {e}")คลาส exception ที่กำหนดเอง
หัวข้อที่มีชื่อว่า “คลาส exception ที่กำหนดเอง”// TypeScriptclass AppError extends Error { constructor( message: string, public readonly code: number ) { super(message); this.name = "AppError"; }}
try { throw new AppError("Not found", 404);} catch (err) { if (err instanceof AppError) { console.log(`[${err.code}] ${err.message}`); }}# Pythonclass AppError(Exception): def __init__(self, message: str, code: int) -> None: super().__init__(message) self.code = code
try: raise AppError("Not found", 404)except AppError as e: print(f"[{e.code}] {e}")ลองเล่นดู
หัวข้อที่มีชื่อว่า “ลองเล่นดู”def divide(a: float, b: float) -> float: if b == 0: raise ValueError("Cannot divide by zero") return a / b
# Successful casetry: result = divide(10, 2) print(f"10 / 2 = {result}")except ValueError as e: print(f"Error: {e}")else: print("No error occurred (else clause)")finally: print("Always runs")
print()
# Error casetry: result = divide(10, 0)except ValueError as e: print(f"Caught: {e}")else: print("This will NOT print")finally: print("Finally again")Loading Python runtime (first run only)…