In our app, we use components developed by other teams. The question was how can I define a nicely way of exception handling than this
try
{
someComponent.DoStuff();
}
catch (Exception ex)
{
textLabel= ex.Message;
}
The component has no custom exception type, maybe a nicely way to do it would be to define a component specific Exception type and wrap this somehow?
I know the question is very basic, but I am interested more in the let’s say how it is good to do it. If you call another component with no custom defined exception types, how do you handle any potential exceptions in an elegant way?
When you catch an error you are able to repackage it and then throw another error, at the most basic level you may just be adding more data – but, from what you’ve suggested, you could also replace the generic error with a custom error that, whilst it won’t overcome the limitations of the response you’ve got from the component, would give the code further up the call stack the opportunity to respond more appropriately.
So in terms of just adding information in the most basic manner – by throwing a new exception with some additional text whilst still passing the original exception:
Now, if you want to define your own custom component exception you change the
new Exceptionto newComponentSpecificExceptionadding data as necessary to the constructor but never forgetting to set the inner exception. Exceptions also have a data collection of key, value pairs into which you can insert more information (by creating the exception, adding the data and then doing the throw).That’s all fairly generic – working forward from there, where you can’t necessarily anticipate all the exceptions you have to handle you don’t try – you set up logging so that you know when you’ve got a generic exception i.e. one that hits the final catch – and then over time add exception specific catches above the generic to provide more appropriate responses or, at the very least, package up the error into less general custom exceptions.
Not sure I’ve explained that very well – but the notion is that as its difficult to anticipate every possible error you want to have a strategy to develop your application in a systematic fashion as you discover new exceptions.