Reputation: 28284
still giving problem
I have the following code. As long as I am in try { } it writes fine. But when there is an error, it doesn't write to log file. Not sure why
private static void jk(string kName, string path)
{
Job job;
try
{
// run some functions here and then write to the file
StreamWriter LJ = new StreamWriter("C:\\Lob.txt");
LJ.WriteLine("XXXXXXXXXXXX");
LJ.Close();
}
catch (InvalidException)
{
StreamWriter LJ = new StreamWriter("C:\\Lob.txt");
LJ.WriteLine("YYYYYYYYYYYYYYYY");
LJ.Close();
Console.WriteLine("Error: ");
return;
}
}
Upvotes: 0
Views: 156
Reputation: 1595
Are you able to compile this code?
There are two things I see incorrect with the above.
It should be InvalidException not IncalidException
try
{
LJ.WriteLine("XXXXXXXXXXXX");
}
catch (InvalidException e)
{
LJ.WriteLine("YYYYYYYYYYYYYYYY");
Console.WriteLine("Error: {0}", e.Message);
return;
}
Upvotes: -1
Reputation: 5355
With your comment:
try fails because of some other problems but I am trying to log it into the file
I assume that the exception is not thrown by LJ.WriteLine("XXXXXXXXXXXX");
If that's the case, you might just need to flush the StreamWriter. Try declaring LJ in a using block like this:
using (StreamWriter LJ = new StreamWriter("C:\\Lob.txt"))
{
LJ.WriteLine("XXXXXXXXXXXX");
try
{
...
LJ.WriteLine("XXXXXXXXXXXX");
}
catch (InvalidException)
{
LJ.WriteLine("YYYYYYYYYYYYYYYY");
Console.WriteLine("Error: ");
return;
}
}
Upvotes: 1
Reputation: 48290
The catch
block executes only when the try
block throws the exception (which appears to be a typo in the original post).
If the try
succeeds, the catch
is never executed.
If the try
fails, it's because of a problem that must have occurred in writing to the log. When the catch
executes, that problem most likely still exists, so the log within the catch
will fail also.
Upvotes: 3
Reputation: 40150
Because the only thing in your try is writing to the stream... and that's the same thing you try to do in the cacth. Why would that work?
Upvotes: 5
Reputation: 124642
Well, I don't know what type LJ
is, and I certainly have never heard of a IncalidException
. I am assuming that you just typed the code into the editor incorrectly. You should really just paste it in to avoid those types of errors.
Anyway, there are a few options:
LJ.WriteLine
is not throwing an exception.LJ.WriteLine
is throwing an exception, but not of the same type you are catching (i.e., see if it works when you just catch { }
).LJ.WriteLine
is also throwing an exception and you are catching (and perhaps swallowing) it further up the stack.Upvotes: 1