What is the better approach when handling errors – throwing it as an exception or returning a an object that contains the error and its details?
I’m thinking what is the better approach to notifying errors – in terms of system resources, coding practices and overall enterprise practices ?
I’ve seen in most cases, the sample code throws a custom exception containing the error information. But I was thinking if it was better to just return an object instantiated from a class (for example: class DatabaseError)?
I believe throwing exceptions in C# can be resource intensive and this would involve having (possibly) a lot of try-catch blocks.
Thanks!
Exceptions are generally considered to be the preferred mechanism for relaying error conditions up the application chain to where they can be dealt with and managed in such a way that they do not cause the application to fail completely and terminate.
However, it is also generally considered poor practice to use the exception-handling mechanism as a logic path – that is, to make the catching of an error condition a prerequisite for later correct or alternative functionality (e.g. to attempt to open a file which may or may not exist, catch the exception if it does not exist, and present a file-browser dialog as a consequence – in this example, the ‘NOT FOUND’ error condition should be detected before attempting to open the file rather than regarding the exception path as the route by which the user is asked to locate it).