How to suppress this warning... C#

Red Squirrel

No Lifer
May 24, 2003
70,561
13,801
126
www.anyf.ca
I have a code block as follows:

try
{
File.Copy("output\\SQLcache.sql.tmp", "output\\SQLcache.sql");
File.Delete("output\\SQLcache.sql.tmp");
}
catch (Exception ex)
{
}

I get a warning every time that ex is declared but never used. I don't want or need to use it, I just want to catch the exception so the whole program does not crash in the case that one of the above files is deleted or missing.
 
Oct 27, 2007
17,009
5
0
You don't even need to declare an exception
try
{
// stuff
}
catch { }

However I would recommend logging exceptions in some way if you're writing anything no-trivial.
 

Red Squirrel

No Lifer
May 24, 2003
70,561
13,801
126
www.anyf.ca
Originally posted by: GodlessAstronomer
You don't even need to declare an exception
try
{
// stuff
}
catch { }

However I would recommend logging exceptions in some way if you're writing anything no-trivial.

Hmm was pretty sure I tried that and it told me a parameter was missing. Seems to work now.
 

jalaram

Lifer
Aug 14, 2000
12,920
2
81
From what I've understood, it's bad practice to catch and ignore exceptions like that. Like GA suggested, you still should log it.

If you know when you're expecting an exception (e.g. missing file), then catch that specifically. I believe it's CFileException.

 

KIAman

Diamond Member
Mar 7, 2001
3,342
23
81
From a design perspective, you should simply check if the file exists before operating on it.

if (File.Exists("output\\SQLcache.sql.tmp"))
{
File.Copy("output\\SQLcache.sql.tmp", "output\\SQLcache.sql");
File.Delete("output\\SQLcache.sql.tmp");
}
 

Crusty

Lifer
Sep 30, 2001
12,684
2
81
Originally posted by: KIAman
From a design perspective, you should simply check if the file exists before operating on it.

if (File.Exists("output\\SQLcache.sql.tmp"))
{
File.Copy("output\\SQLcache.sql.tmp", "output\\SQLcache.sql");
File.Delete("output\\SQLcache.sql.tmp");
}

From a performance standpoint try/catch is faster than checking for error conditions before you operate.
 

Snapster

Diamond Member
Oct 14, 2001
3,916
0
0
Log it to file or:

catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}

 

seemingly random

Diamond Member
Oct 10, 2007
5,277
0
0
Originally posted by: RedSquirrel
I have a code block as follows:

try
{
File.Copy("output\\SQLcache.sql.tmp", "output\\SQLcache.sql");
File.Delete("output\\SQLcache.sql.tmp");
}
catch (Exception ex)
{
}

I get a warning every time that ex is declared but never used. I don't want or need to use it, I just want to catch the exception so the whole program does not crash in the case that one of the above files is deleted or missing.
Did you try the above without ex?

ie. catch (Exception)