How to manage exception in catch block c#?

I have following code.

try
{
    int s=10;
    int k=0;
    int stdsd = s / k;
}
catch (DivideByZeroException ext)
{
    FileStream fs = new FileStream(@"C:\temp\data.txt", FileMode.Open);  
    //encountered an exception as file doesn't exist.
}
catch (Exception ex)
{
}
finally
{
    //some code here.
}

In above code when exception occured then it will try to write that in one file in catch block.but when it trying to open that file that file doen't exists, so in such cases system crashed. I want to execute such critical code in finally block but due to exception in catch block it not going further to that line.

I know we can check file exists check but I don't want to check file exist check over here, I want to how to manage that in catch block. can please assist the best way to manage exception in catch block.

Jon Skeet
people
quotationmark

You can't handle the exception generated from one catch block in a catch block associated with the same try/catch statement. Instead, you need an extra one:

catch (DivideByZeroException ext)
{
    try
    {
        FileStream fs = new FileStream(@"C:\temp\data.txt", FileMode.Open);  
    }
    catch (IOException e)
    {
        // Handle the exception here
    }
}

Note that you should be using a using statement when opening the stream, so that you'll close it automatically whether or not an exception is thrown later.

I'd also recommend not having the code like this in the catch block directly - typically catch blocks should be short, for readability. Consider moving all the error-handling functionality into a separate method (or possibly even a separate class).

people

See more on this question at Stackoverflow