Calling Console.WriteLine(ex.Message) to prevent warning message

Nap picture Nap · Jun 29, 2009 · Viewed 16.4k times · Source

We usually catch exception in the upper level of a code like the GUI (forms).

But I usually have this kind of code

try
{
}
catch(Exception ex)
{
  Console.WriteLine(ex.Message);
  MessageBox.Show("Application has encountered error....");
}

I could just catch(Exception) without the identifier because I do not need the message on runtime, but for the debugging build, it sure is convenient to break at the catch statement. So I usually write a Console.WriteLine to prevent a lot of warning of unused ex variable. I have a lot of case of Console.WriteLine(ex.Message) in my code. Does this cost performance decrease?

Note: Changed title from "Does Console.WriteLine(ex.Message) have performance cost?" to "Calling Console.WriteLine(ex.Message) to prevent warning message"

Answer

Sam Saffron picture Sam Saffron · Jun 29, 2009

This is a multiple question in 1 so I will try to unroll it:

Firstly

try{
  ...
}
catch(Exception) 
{
}

Is perfectly valid syntax. Adding a Console.WriteLine(ex.Message) just to get the thing to compile without warning is not the right thing to be doing.

Secondly

Console.WriteLine is not the proper way to do diagnostics, look at Trace.WriteLine or better still a Logging framework. Of course Console.Writeline has a cost, the cost is not too serious, nonetheless a call is made, and it has a cost.

Thirdly

Sometimes its better to crash, it forces you to fix the root problem, at least do a Debug.Assert if something really bad happens.