This a code is 10 years old, without error handling. The code comes from a simple script interpreter without parser or scanner, I’m trying catch all errors in the interpreter and return a suitable error with error message.
//..
//...
// <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;
}
}
Note: as shown in code above, I’m throwing the ErrorInScriptException in three cases, I change only the message.
[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;
}
This is usually ok. However, if you intend those exceptions to be caught and dealt with by code (instead of just signalling an error that the user has to deal with), you might want to create appropriate subclasses that detail the kind of error.
I.e.
But unless those exceptions are intended for code to react to different errors differently I don’t think this makes much sense. To a user the exception message is relevant and that could be achieved with any Exception class.