我有以下代码来打开文件并处理错误:
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
这里有什么问题?谢谢!
最佳答案
表示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
此外,您可能不需要调用 clone
在 file_name_abs
,但这是次要问题,而不是您看到的运行时错误的原因。
[更新]:要在运行时处理错误,您有几个我知道的选项:
选项 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)
}
关于rust - 使用rust 中未发现的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21372100/