Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinguish between exception of same type

What is the best method to distinguish between two exception of the same type but thrown for different reasons.

For example InvalidOperationException can be thrown attempting to access an empty sequence, but it can also be thrown when using the Concurrent object (e.g. BlockingCollection)

From my reading I've taken the conclusion that using the BlockingCollection.CompleteAdding() to signal completion is perfectly fine and as such one would need to catch the Exception and handle appropriately (exit the task for instance)

What is the best way to filter these without having to use the message content?

Edit: They both appear to have the same HResult value.

like image 310
galford13x Avatar asked Dec 15 '15 04:12

galford13x


1 Answers

AFAIK you can differentiate between two Exceptions of the same Type only by the Message.

However, you should not rely on the Message to make Catch decisions. The Message may be localized depending on the locale configuration of the system you are executing your code on. This will make your Catch When block not relevant if the language of the system is different than the language of the Message you hard-coded.

The only case where you can use the Message is when you are the system administrator and writing a software for a server you will be managing and you are sure that the language you are using will not change in the future (which cannot be guaranteed when you write a software for to run on client devices).

like image 149
Mohammed Noureldin Avatar answered Sep 23 '22 02:09

Mohammed Noureldin