Reputation: 1284
I'm trying to define custom file parse exception class, which to holds information - the name of the file and the line of the file on which the exception is happening.
class FileParseException : Exception {
string fileName;
long lineNumber;
public FileParseException() {
}
public string GetFileName() {
return fileName;
}
public long GetLineNumber() {
return lineNumber;
}
}
How should I store the data for the current file and when it rises an exception to access it through thy-catch block:
try {
// some code here
}
catch (FileParseException fpe) {
Console.WriteLine(fpe.getLineNumber);
}
Upvotes: 0
Views: 498
Reputation: 244797
First, C# has properties, so you should use them, not create GetXXX
methods. In your case, public automatic properties with private setters should do the job:
public string FileName { get; private set; }
public long LineNumber { get; private set; }
You can set them in a constructor of the exception:
public FileParseException(string fileName, long lineNumber)
{
FileName = fileName;
LineNumber = lineNumber;
}
To throw such exception, use the constructor above:
throw new FileParseException(fileName, lineNumber);
And when you catch it, you can access the properties:
catch (FileParseException fpe)
{
Console.WriteLine(
"Error in file {0} on line {1}.", fpe.FileName, fpe.LineNumber);
}
Also, you should probably set the Message
of the exception, by passing the message to the base constructor:
public FileParseException(string fileName, long lineNumber)
: base(
string.Format(
"Error while parsing file {0} on line {1}.", fileName, lineNumber))
{
FileName = fileName;
LineNumber = lineNumber;
}
Upvotes: 2