Try .. Catch .. and Continue? [C#]

Shaitan00

Junior Contributor
Joined
Aug 11, 2003
Messages
358
Location
Hell
Inside my {Try} I attempt to load a file [StreamReader], if this fails (for example the file is not there) the error is caught in the {Catch} and the function terminates [exits {Try}].

Problem is I do not want the application to stop because it was unable to load the file, is there a way to catch the error [inside the {Catch} I would log the error to file] and then return to the {Try} section to continue processing?
 
Last edited:
Easy

Code:
Try
    [Code to try and open the the file]
Catch ex as FileNotFoundException
    [Clean up Code]
End Try

[continue with what you wanted to do]

Remember that try catch statements can be nested and son't have to be generic.
 
In most cases a Try block should only contain one or two statements. However more often than not one comes across blocks with multiple lines of code shoved into them, which is a poor practice at best.

The steadfast rule is: keep the number of lines to a minimum, and the exceptions specific.

What should you do if code that follows the Try/Catch block shouldn't execute if an exception was thrown? Change a boolean variable in the Catch block and use If/Then logic to detect the outcome.
 
Shaitan00 said:
Problem is I do not want the application to stop because it was unable to load the file, is there a way to catch the error [inside the {Catch} I would log the error to file] and then return to the {Try} section to continue processing?

There is no continue statement that acts like a loop. However you can create your own loop;

bool processing = true;
while (processing) { ... }

In your try block, set processing to false (as you're obviously done if the code succeeds). In your catch block, set processing to false (an error occured, try again).
 
Back
Top