Ra1nWarden
Ra1nWarden

Reputation: 1220

Uncaught error in rust

I have the following code to open a file and handle errors:

match File::open(&Path::new(file_name_abs.clone())) {
   Some(html_file) => {
       let mut html_file_mut = html_file;
       let msg_bytes: ~[u8] = html_file_mut.read_to_end();
       response.push_str(str::from_utf8(msg_bytes));
   },
   None => {
       println("not found!");
       valid = false;
   }   
}

Still when I pass in an invalid file, I have the following error message:

task '<unnamed>' failed at 'Unhandled condition: io_error: io::IoError{kind: FileNotFound, desc: "no such file or directory", detail: None}', /private/tmp/rust-R5p2/rust-0.9/src/libstd/condition.rs:139

What is wrong here? Thanks!

Upvotes: 1

Views: 425

Answers (1)

quux00
quux00

Reputation: 14624

It means that the file described by file_name_abs is not found at the location you specified. Check the path of the file.

I ran this code (slightly modified) on my system. It works if the file is found and gives the "file not found" error if it is not, like so:

task '<main>' failed at 'Unhandled condition: io_error: io::IoError{kind: FileNotFound, desc: "no such file or directory", detail: None}', /home/midpeter444/tmp/rust-0.9/src/libstd/condition.rs:139

Also, you probably don't need to be calling clone on file_name_abs, but that is a secondary concern and not the cause of the runtime error you are seeing.

[Update]: to handle the error at runtime you have a couple of options that I know of:

Option 1: Check that the file exists before trying to open it:

let fopt: Option<File>;
if path.exists() && path.is_file() {
    fopt = File::open(&path);
} else {
    fopt = None;
}
// then do the match here


Option 2: Use the io::result function: http://static.rust-lang.org/doc/0.9/std/io/fn.result.html. This function will trap any IO error and allow you check the Result<T,Error> it returns to see if it succeeded or threw an error. Here's an example:

let path = Path::new(fname);

let result = io::result(|| -> Option<File> {
    return File::open(&path);
});

match result {
    Ok(fopt)      => println!("a: {:?}", fopt.unwrap()),
    Err(ioerror)  => println!("b: {:?}", ioerror)
}

or, more idiomatically, (as pointed out by @dbaupp):

let path = Path::new(fname);

let result = io::result(|| File::open(&path));

match result {
    Ok(fopt)      => println!("a: {:?}", fopt.unwrap()),
    Err(ioerror)  => println!("b: {:?}", ioerror)
}

Upvotes: 1

Related Questions