NZEC คือ Non-Zero Exit Code
Exit Code คือรหัส (ตัวเลข) ที่โปรแกรมคืนให้ Operating System เมื่อจบการทำงาน:
- Exit Code 0: จบสำเร็จ (Successful Termination)
- Non-Zero Exit Code: จบล้มเหลวเนื่องจาก Error (Failed Termination)
เนื่องจาก Python รองรับ Exception Handling เราสามารถใช้ try-except จับ Error นี้ได้
NZEC Error เป็น Runtime Error เกิดขึ้นมักเมื่อ:
- เข้าถึง Array ด้วย Index ติดลบ
- โปรแกรมใช้ Memory มากกว่าที่จัดสรรไว้
- Recursion ลึกเกินไป (Stack Overflow)
- หารด้วยศูนย์ (Division by Zero)
- Integer Overflow
การจัดการ NZEC ใน Python
try:
# โค้ดที่อาจเกิด Error
pass
except Exception as e:
# จัดการ Error
pass
สาเหตุทั่วไปและวิธีแก้
1. การรับ Input ผิดรูปแบบ
# ผิด - ไม่มี split() x, y = map(int, input()) # ถูก - ใช้ split() แยกด้วย whitespace x, y = map(int, input().split())
2. การอ่าน Input หลายบรรทัด
# ผิด - อาจ NZEC หาก Input ไม่ครบ
for i in range(n):
x = int(input())
arr.append(x)
# ถูก - อ่านทั้งบรรทัดแล้ว split
arr = list(map(int, input().split()))
# หรือ
arr = [int(k) for k in input().split()]
3. Infinite Recursion / Stack Overflow
- ตรวจสอบ Base Case ของ Recursive Function
- เพิ่ม Recursion Limit:
sys.setrecursionlimit(10**6)
4. Memory Limit Exceeded
- ใช้ Generator แทน List สำหรับข้อมูลใหญ่
- หลีกเลี่ยงการเก็บข้อมูลไม่จำเป็น
5. Edge Cases / Corner Cases
- ทดสอบกับ Input ขอบเขต (0, 1, ค่าสูงสุด, String ว่าง, ฯลฯ)
- ตรวจสอบ Division by Zero
- Factorial มากกว่า 20 อาจ Overflow ในบางภาษา (Python ไม่มีปัญหาเพราะ Big Int)
Tip สำหรับ Competitive Programming
- Platforms เช่น CodeChef ไม่แสดง Error Code ต้อง Debug เอง
- ใช้
try-exceptครอบโค้ดหลัก เพื่อไม่ให้ Crash - ตรวจสอบ Input/Output Format ให้ตรงกับ Spec อย่างแม่นยำ