Call Console.WriteLine (ex.Message) to prevent a warning

Usually we get an exception at the top level of code, such as GUI (forms).

But I usually have code like this

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

I could just catch (exception) without an identifier, because I do not need a message at runtime, but to build debugging, of course, it’s convenient to break it down on the output. Therefore, I usually write Console.WriteLine to prevent a lot of warnings about an unused ex variable. In my code, I have many cases of Console.WriteLine (ex.Message). Does this reduce the cost?

Note. Changed the name from "Does Console.WriteLine (ex.Message) cost the execution?" to "Call Console.WriteLine (ex.Message) to prevent a warning"

+3
6

1, :

-

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

. Console.WriteLine(ex.Message) , - , .

-

Console.WriteLine - , Trace.WriteLine . , Console.Writeline , , , , .

-

, , Debug.Assert, - .

+10

, .

public static Exception
{

    [Conditional("DEBUG")]
    public static void Dump( this Exception ex )
    {
        Console.WriteLine( ex.ToString() );
    }
}

...

public static Exception
{
    public static void Log( this Exception ex )
    {
#if DEBUG
        Console.WriteLine( ex.ToString() );
#endif
        Logger.WriteLine( ex.ToString() );
    }
}

Console.WriteLine( ex.ToString() ) ex.Log();

, , , .

+6

System.Diagnostics.Debug.WriteLine(ex) System.Diagnostics.Trace.WriteLine(ex). - , DEBUG , Trace - TRACE. DEBUG.

+3

. , .

, , - , winforms, ex.Message, ex.ToString(). ?

+2

: "" ex ", " catch, , , :

try
{
    ...
}
catch(Exception)    // avoid warning
{
   // set break point inside exception
}

$exception , Visual Studio (2008).

+2

# , . , - :

  • Create a list of strings
  • In this list, make 25% of them a number, and the rest with one letter.
  • Run a for loop going through each list and do int foo = (int) myList [0], but wrap it in try / catch.

Increase your bid to 50%, then 75%, then 100%. 100% will be a little slower, but not by much.

In this particular example, the real-world response would be to use Int32.TryParse instead, but it shows you a fine.

0
source

Source: https://habr.com/ru/post/1711460/


All Articles