Error Handling
ในภาษาอื่น เราอาจจะคุ้นเคยกับ try-catch หรือการเช็ค null แต่ใน Rust เราไม่มี Exception และไม่มี Null ครับ Rust แยก Error ออกเป็น 2 ประเภทใหญ่ๆ:
- Recoverable Errors: แก้ไขได้ ไปต่อได้ (ใช้
Result<T, E>) - Unrecoverable Errors: พังยับเยิน ไปต่อไม่ได้ (ใช้
panic!)
ลองนึกภาพว่า Error Handling เป็นเหมือน “แผนสำรอง” - ถ้าเกิดปัญหาจะทำยังไง?
1. Panic! - Unrecoverable Errors
Section titled “1. Panic! - Unrecoverable Errors”1.1 Basic Panic
Section titled “1.1 Basic Panic”fn main() { // ============================================ // panic!() = หยุดโปรแกรมทันที // ใช้เมื่อเกิด bug ที่ไม่สามารถแก้ไขได้ // ============================================ panic!("Something went terribly wrong!");}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google