Archive

Posts Tagged ‘Exceptions’

HowTo: show inner exception message if available, else outer one

Sometimes when you catch an exception in .NET, the message it prints out isn’t very informative, since it is wrapping another exception that had been thrown a bit inner in the code. That exception is in that case accessible via InnerException of the Exception instance.

That inner exception is also an Exception, so one would like to use its Message instead of the outer exception’s one, if an inner exception exists and, only if an inner exception doesn’t exist use the caught exception’s message. Here’s a clean-looking pattern I’ve coined up to achieve this while working on the TrackingCam application:

try

{

  //…

}

catch (Exception e)

{

  MessageBox.Show((e.InnerException ?? e).Message);

}

the ?? operator returns e.InnerException if it is not null, else falls back to returning e. Those two results are both of type Exception, so you can use Message on them, by putting the ?? operator’s expression in parentheses.

Suggestion: implement ignore keyword or allow missing catch block in C#

This is a suggestion I’ve just sent in via Visual Studio’s “Send a frown” feature (rewritten here a bit differently from memory, since that feedback channel doesn’t allow you to access your previous feedback as the Microsoft Connect or the Uservoice site does) :

Instead of having to write

try
{

}
catch (SomeExceptions)
{
//NOP (ignored)
}

I’d like to be able to write

try
{

}
ignore (SomeExceptions);

and similarly if a finally block is used, allow:

try { … }

ignore(SomeExceptions)

finally { … };

That is, I suggest adding an “ignore” keyword, introduced to C# in order to ignore specific exceptions.

Alternatively, could allow a missing catch block, so that the catch (…) clause would be able to be followed directly by a “;” to end the try/catch statement, or by a “finally” clause and its code (sub)block.

try
{

}
catch (SomeExceptions);

and when finally block is used:

try {…}

catch(SomeExceptions)

finally { … }

I’ve also uploaded this for voting up here:
http://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/9453432-implement-ignore-keyword-or-allow-missing-catch-bl

%d bloggers like this: