用实例学习 Rust——panic! 让我们的程序崩溃吧

用实例学习Rust——panic!让我们的程序崩溃吧

今天来看看如何在 Rust 中主动抛出异常。当然,验证代码的行为是否如我们所想,写测试!还是新建一个库项目,删掉自动生成的代码,开始写我们自己的测试。

首先来看看主动抛出异常的最简单方式,panic! 宏。

#[cfg(test)]
mod tests {
  #[test]
  #[should_panic]
  fn test_simple_panic() {
    panic!();
  }
}

为了测试异常,需要加上 #[should_panic] 标注,因为我们没有办法在代码中捕获异常。

下面看看在日常写代码过程中最简单触发异常的方式:

#[test]
#[should_panic]
fn test_option_unwrap() {
  None::<i32>.unwrap();
}

我们知道 unwrap 函数是从 Option 类型中把真实值取出来,但是如果 OptionNone 类型,调用这个函数就会发生异常了。

我们还可以自定义发生异常的信息,便于查找和调试:

#[test]
#[should_panic(expected = "异常信息")]
fn test_expect() {
  None::<i32>.expect("异常信息");
}

在之前的文章中我们已经使用过 expect 函数了。同样我们需要给标注加入参数。

panic! 宏同样可以携带自定义错误信息,还可以格式化信息:

#[test]
#[should_panic(expected = "异常信息")]
fn test_panic_message() {
  panic!("异常信息");
}

#[test]
#[should_panic(expected = "异常信息")]
fn test_panic_format() {
  panic!("{} 异常信息", "这里是");
}

panic! 宏还可以返回数字:

#[test]
#[should_panic]
fn test_panic_return_number() {
  panic!(42);
}

最后再说一个可以产生异常的语句是 assert! 宏,没错,就是我们用来写单元测试常用的判断语句。

#[test]
#[should_panic]
fn test_assert() {
  assert!(1 == 2);
}

#[test]
#[should_panic]
fn test_assert_eq() {
  assert_eq!(1, 2);
}

#[test]
#[should_panic]
fn test_assert_neq() {
  assert_ne!(1, 1);
}

最后的最后,大家运行测试程序看看结果。如有任何问题,请添加微信公众号“读一读我”。