ข้ามไปยังเนื้อหา

Error Handling

การจัดการ error ของ Python แมปเข้ากับ try/catch/finally ของ TypeScript โดยตรง — พร้อมส่วนเสริมที่ทรงพลังหนึ่งอย่าง: ประโยค else ที่จะทำงานก็ต่อเมื่อ ไม่มี exception ถูก raise คีย์เวิร์ดคือ try/except/else/finally และคุณใช้ raise เพื่อโยน exception แทน throw

TypeScript
// TypeScript
function 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");
}
Python
# Python
def 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 เข้ากับตัวแปร
TypeScript
// TypeScript
try {
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
# Python — multiple except clauses
import 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}")
TypeScript
// TypeScript
class 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}`);
}
}
Python
# Python
class 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 case
try:
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 case
try:
result = divide(10, 0)
except ValueError as e:
print(f"Caught: {e}")
else:
print("This will NOT print")
finally:
print("Finally again")
อะไรคือสิ่งที่เทียบเท่า `throw new Error("msg")` ของ JavaScript ใน Python?
ประโยค `else` ของบล็อก `try` ทำงานเมื่อใดใน Python?
จะจับ exception หลายชนิดในประโยค `except` เดียวได้อย่างไร?
บล็อก `finally` ทำงานเมื่อใด?