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);
}
First, C# has properties, so you should use them, not create
GetXXXmethods. In your case, public automatic properties with private setters should do the job:You can set them in a constructor of the exception:
To throw such exception, use the constructor above:
And when you catch it, you can access the properties:
Also, you should probably set the
Messageof the exception, by passing the message to the base constructor: