1

What is ideomatic way of handling methods which can panic. For example take a look at next code

fn main() {
    let v = [1, 2];
    let b = v.split_at(4);
    println!("{:?}", b);
}

split_at will panic because array doesn't have element at index 4, but how i can handle it as rust has not try catch

Victor Orlyk
  • 1,454
  • 2
  • 15
  • 27
  • Well, in theory you can catch panics, even though it's usually not the right thing to do. Functions that panic and for which you would like to handle the error yourself usually have a `try_` version. It's not the case of this function, because in this case you can just check the length yourself beforehand. – jthulhu Jan 25 '23 at 09:33
  • i understand about methods which can return Result, but methods which do not return result and have no try__ is kinda stange. In this particular things one can check for len but then we can almost always do extra check i don't think this is connected to error handling – Victor Orlyk Jan 25 '23 at 09:36
  • Not necessarily. Actually, there are quite a lot of functions that you don't expect that could `panic!`, but can, in some very adverse situations in which there isn't much you can do to handle the error anyways. For instance, `Box::new` can fail if there is no more memory available. In this case, there is literally nothing you can do to handle the error *except if your program has a special mode where it doesn't not require any more memory* which is extremely unlikely. – jthulhu Jan 25 '23 at 09:37
  • Also, `split_at` is just a wrapper around `split_at_unchecked`. Basically, `split_at` just adds a panicking check before calling `split_at_unchecked`. If you don't want to panic, you should probably not use `split_at` and write your own non-panicking check. – jthulhu Jan 25 '23 at 09:39
  • 2
    if you ask me this function is a design mistake and should have returned an option or result – Stargateur Jan 25 '23 at 09:44
  • https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=ba5faa87ba4fd47c5836eeddfb4b1ae8 – Stargateur Jan 25 '23 at 09:52
  • @jthulhu [`Box::try_new()` exists](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#method.try_new) (albeit unstably). Also, OOM does not panic by default but aborts. – Chayim Friedman Jan 25 '23 at 10:20

0 Answers0