I like the idea of throwing an exception instead of returning null
or other error-value. Let's say I'm designing a new class that parses an XML of a certain format. I would like my class to have just one entry point, that is, a constructor that specifies the path to a valid XML file. In return, I get an object with a bunch of properties and methods that holds the content of my XML file and gives me some information about it.
Now, for example, how can I make sure that my path to the XML file was valid? I can have, say, a Load(string xmlPath)
function in my class. What should be its return type? Should it return a bool
or int
or what? And, most interesting, how can I check that? Ideally I should make the Load
function private
, and don't even care that it exists. But if I want to check the result of Load
, then the function should be made public
. Or, pass a bool loadSuccesful
variable to my constructor and fill that with the result of loading the file. But wait, what if I want to check my XML
file against an XSD
? I'll have to have another function, parseXmlSchema(string xmlPath)
or something like that. What should it return on failure? And how can you get the information out of your class while keeping a clean interface at the same time? Other validations could also be necessary.
While, if you make these kinds of methods private, and throw an exception when something goes wrong (there really is no point in parsing your XML file if it's not valid), you can have a clean interface an use your class in a try/catch
statement. You can have your class constructor with only one string
parameter (or two, if you count the XSD
schema). If all is well in the try
statement, if nothing went wrong, no exceptions thrown, paths exists, etc. your program is happy. If you're currently in the middle layer of your app and get an FileNotFoundException
from your lower layers, you can rethrow
that and pass it to your user (GUI) to do something about it. The GUI layer could catch it at this moment and alert the user, through a messageBox, for example, and log it as a bonus. The user then tries another XML file, and on goes the story. If you catch all possible exceptions and display meaningfull information to the user or take the appropriate measures in the background, there is no need for your application to freeze (you've likely seen that), if that's what you're afraid of.
As a bonus, you can pass all kind of meaningful information at the point your exception was thrown, like messages, parameter names, line numbers, function name, etc. If you document your code (as you should), document the exceptions that a class/method can throw.