私はシリアルポート経由で通信する制御回路を持っています。応答コマンドが特定の形式と一致しない場合、私はそれをエラーとみなし、エラーコードを返すべきか、例外をスローするべきか疑問に思っていましたか?例:C#エラーコード対例外
public double GetSensorValue(int sensorNumber)
{
...
string circuitCommand = "GSV,01," + sensorNumber.ToString(); // Get measurement command for specified sensor.
string responseCommand;
string expectedResponseCommand = "GSV,01,1,OK";
string errorResponseCommand = "ER,GSV,01,1,62";
responseCommand = SendReceive(circuitCommand); // Send command to circuit and get response.
if(responseCommand != expectedResponseCommand) // Some type of error...
{
if(responseCommand == errorResponseCommand) // The circuit reported an error...
{
... // How should I handle this? Return an error code (e.g. -99999) or thrown an exception?
}
else // Some unknown error occurred...
{
... // Same question as above "if".
}
}
else // Everything is OK, proceed as normal.
...
}
ありがとう!
興味深いでてくる可能性があっても、取り扱いが容易です。私は標準的なエラー処理の例外を推奨することに驚いています。珍しいまたは予期せぬ状況の例外を予約しませんか? –
@JohnWeldon:いいえ、私はエラーのために呼び出しコードがすべてが大丈夫だったかのように進んではならないことを意味します。 "*応答コマンドが特定の形式と一致しない場合、私はそれをエラーとみなします。" –
プログラムの通常の流れはこのケースを扱うことを意図していませんか?私はその場合の例外の使用に同意します。しかし、プログラムが通常このエラー状態に応答すると予想される場合、私は例外を使用しません。質問の私の解釈は後者でしたが、前者は同じように妥当であろう。 –