Exceptional Messages
by in CodeSOD on 2023-03-30Structured exception handling is an excellent way to handle errors, but wouldn't it be nice if you could execute a different branch of code depending on what specific error just happened? It's a pity that there's just no possible way to filter exceptions using the good old fashioned try and catch. Fortunately, Mateusz has a co-worker who invented that wheel for us.
if (something_bad_happens)
throw new Exception("File is not correct; 88888");
if (something_else_happens)
throw new Exception("Tag len exceeded; 1337");
...
catch (Exception ex)
{
if (ex.Message.Contains("88888"))
{
...
}
else if (ex.Message.Contains("1337"))
{
...
}
}