Skip to content
เข้าสู่ระบบ

Panic - โปรแกรมพัง

std::panic สำหรับจัดการเมื่อโปรแกรมเจอ error ร้ายแรงที่ไม่คาดคิด! Panic เป็นกลไกสำคัญของ Rust ที่ช่วยให้โปรแกรม fail อย่างปลอดภัย

Panic คือการหยุดโปรแกรมทันทีเมื่อเจอ error ที่:

  • ไม่คาดว่าจะเกิด (bug ใน code)
  • ไม่สามารถ recover ได้อย่างสมเหตุสมผล
  • แสดงว่ามีอะไรผิดปกติร้ายแรง (invariant ถูกละเมิด)

Panic vs Error - เลือกใช้อย่างไร?

Section titled “Panic vs Error - เลือกใช้อย่างไร?”
use std::fs::File;
use std::io::Read;
fn main() {
// ============================================
// panic! ใช้สำหรับ "bugs" - สิ่งที่ไม่ควรเกิด
// ============================================
fn divide(a: i32, b: i32) -> i32 {
if b == 0 {
// ใน library code ควรใช้ Result แทน
// แต่ถ้า caller ควรรู้ว่าห้ามส่ง 0 = panic
panic!("Division by zero! This is a bug in caller's code");
}
a / b
}
// ============================================
// Result ใช้สำหรับ errors ที่คาดไว้
// ============================================
fn read_config(path: &str) -> Result<String, std::io::Error> {
// ไฟล์อาจไม่มี = expected error, ไม่ใช่ bug
let mut file = File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
// ใช้งาน
println!("10 / 2 = {}", divide(10, 2));
match read_config("config.toml") {
Ok(config) => println!("Config: {}", config),
Err(e) => println!("Config not found: {} (expected!)", e),
}
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด