Bas*_*ili 0 c# exception-handling
这段代码已有10年历史,没有错误处理.代码来自一个没有解析器或扫描程序的简单脚本解释器,我正在尝试捕获解释器中的所有错误并返回带有错误消息的合适错误.
//..
//...
// <exception cref = "ErrorInScriptException">Wrong number of tokens.</exception>
// <exception cref = "ErrorInScriptException">Variable not found.</exception>
// <exception cref = "ErrorInScriptException">Variable type is not string.</exception>
// <param name = "splitScriptLine">Split script line to be interpreted.</param>
private void MakeString(IList<string> splitScriptLine)
{
//check minimum of 3 tokens
if (Tokens < 3)
{
throw CreateErrorInScriptException("IDS_Invalid_Token");
}
var dummy = string.Empty;
//read strings
for (var z = 2; z < Tokens; z++)
{
dummy = dummy + ReadStringToken(splitScriptLine[z]);
}
var variable = VariableList[splitScriptLine[1], FileIncludeLevel];
//no string var detected
if (variable == null)
{
throw CreateErrorInScriptException("IDS_116");
}
//write new string to destination var
if (variable.Identifier.Equals(splitScriptLine[1]))
{
//variable found
if (variable.VariableType !=
VariableType.String)
{
throw CreateErrorInScriptException("IDS_113");
}
variable.Value = dummy;
variable.IsVarString = true;
}
}
Run Code Online (Sandbox Code Playgroud)
注意:如上面的代码所示,我在三种情况下抛出ErrorInScriptException,我只更改了消息.
[Serializable]
public class ErrorInScriptException : UniLoadApplicationException
{
#region Constructors
public ErrorInScriptException(string error)
: base(error)
{
}
#endregion Constructors
#region Properties
public string ErrorCode { get; set; }
public string FileName { get; set; }
public int LineNumber { get; set; }
public string ScriptLine { get; set; }
#endregion Properties
}
/// <summary>
/// Creates a script error.
/// </summary>
/// <param name = "message">Message to be shown.</param>
/// <returns>ErrorInScriptException or the script error.</returns>
protected Exception CreateErrorInScriptException(string message)
{
var ex = new ErrorInScriptException(message)
{
ScriptLine = CurrentScriptLine,
LineNumber = CurrentLineNumber,
FileName = CurrentFileName,
ErrorCode = message
};
ex.Data["Info"] = new ExceptionInfo(ErrorLevel.Error, message)
{
ExitApplication = false
};
return ex;
}
Run Code Online (Sandbox Code Playgroud)
这通常没问题.但是,如果您希望通过代码捕获和处理这些异常(而不仅仅是发出用户必须处理的错误信号),您可能需要创建详细说明错误类型的相应子类.
即
class InvalidTokenException : ErrorInScriptException {}
class NoStringVarException : ErrorInScriptException {}
...
Run Code Online (Sandbox Code Playgroud)
但除非这些例外是针对代码以不同的方式对不同的错误作出反应,否则我认为这没有多大意义.对于用户,异常消息是相关的,并且可以使用任何Exception类来实现.
| 归档时间: |
|
| 查看次数: |
163 次 |
| 最近记录: |