我有以下代码来打开文件并处理错误:
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;
}
}但是,当我传入一个无效的文件时,我仍然会收到以下错误消息:
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这里怎么了?谢谢!
发布于 2014-01-27 03:35:29
这意味着在您指定的位置找不到file_name_abs描述的文件。检查文件的路径。
我在我的系统上运行了这段代码(略有修改)。如果找到该文件,它就会工作,如果没有找到,则会给出“未找到的文件”错误,如下所示:
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另外,您可能不需要在file_name_abs上调用file_name_abs,但这是次要的问题,而不是您所看到的运行时错误的原因。
Update:要在运行时处理错误,我知道以下几个选项:
选项1:在尝试打开文件之前检查文件是否存在:
let fopt: Option<File>;
if path.exists() && path.is_file() {
fopt = File::open(&path);
} else {
fopt = None;
}
// then do the match here选项2:使用io::result函数:http://static.rust-lang.org/doc/0.9/std/io/fn.result.html。此函数将捕获任何IO错误,并允许您检查它返回的Result<T,Error>是否成功或抛出错误。下面是一个例子:
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)
}或者,更具体地说,(正如@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)
}https://stackoverflow.com/questions/21372100
复制相似问题