我正在使用 boost 庫中的以下 C 代碼:
try{
child c(commandString, (std_out & std_err) > pipe_stream);
} catch(process_error &pe){
cout<<pe.what()<<" second line"<<endl;
}
commandString 是一個類似于命令ls或任何其他命令的命令。但是,如果根據檔案鍵入不存在的命令,則會引發process_error例外。
我在這里捕獲例外,但不確定是否有比pe.what()上面更好的方法來列印例外或錯誤的詳細資訊?
uj5u.com熱心網友回復:
如果你看一下升壓參考有關boost::process::process_error,你可以看到這一點:
struct process_error : public system_error { };它僅繼承 std::system_error ,但隨后可以在 catch 塊中與其他系統錯誤區分開來。
強調我的
如果您查看std::system_error參考,就像所有其他標準例外一樣,what()是提供有關引發錯誤的詳細資訊的方法,所以我會說是的,這是列印出例外詳細資訊的正確方法。
但是由于boost::process::process_error沒有覆寫該what()函式,它會回傳與 a 相同的回傳值std::system_error。
uj5u.com熱心網友回復:
另一種介面是使用std::error_code.
有優點也有缺點:
PRO:它使您能夠獲得有關錯誤情況發生位置的更多詳細資訊。(這是一個假設的差異,因為沒有指定是否
what()可能包含超出錯誤條件的資訊)CON:它可能沒有像例外訊息中那樣詳細
CON:由于某些錯誤是例外的,因此很難在介面中表達可能的錯誤條件:錯誤條件以例外不會的方式阻礙
在您的代碼中,您可能通過處理例外創建了這個問題:現在如何決定回傳什么值
中立:您可能仍然需要處理例外,因為例外可能來自任何相關代碼(例如,在設定期間,進行分配)。
中性: 的
code()成員boost::process::process_error可能與error_code您獲得的成員100% 相同
演示
對比下面的實作和輸出:
住在 Coliru
#include <boost/process.hpp>
#include <iostream>
namespace bp = boost::process;
int using_exceptions(std::string const& commandString) {
try {
bp::pstream pipe_stream;
bp::child c(commandString, (bp::std_out & bp::std_err) > pipe_stream);
c.wait();
return c.exit_code();
} catch (std::exception const& e) {
std::cerr << "Exception: " << e.what() << std::endl;
return -1; // WHAT TO RETURN
}
}
int using_error_code(std::string const& commandString) {
try {
bp::pstream pipe_stream;
std::error_code ec;
bp::child c(commandString, (bp::std_out & bp::std_err) > pipe_stream,
ec);
if (ec) {
std::cerr << "Cannot spawn child process: " << ec.message() << "\n";
return -1; // WHAT TO RETURN?
} else {
c.wait(ec);
std::cerr << "Error: " << ec.message() << "\n";
return c.exit_code();
}
} catch (std::exception const& e) {
std::cerr << "Exception: " << e.what() << std::endl;
return -1; // WHAT TO RETURN
}
}
int main()
{
auto cmd = "/usr/bin/bogus";
std::cout << "Using error_code: " << using_error_code(cmd) << "\n";
std::cout << "Using exceptions: " << using_exceptions(cmd) << "\n";
}
印刷
Using error_code: Cannot spawn child process: No such file or directory
-1
Using exceptions: Exception: execve failed: No such file or directory
-1
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/328262.html
