Link to home
Start Free TrialLog in
Avatar of karakav
karakav

asked on

C#: How to ignore an exception and continue processing

Hi,
I am building a web application in which I have a method that processes information that I get from a text file. If I encounter an error, the method stops. I would like to process the data in the file until the end, whatever error I encounter in the way. For that I would like a mechanism that allows me to put the error I encouter in a String variable and then read that string when I get done processing all the file. How can I do that.

Avatar of Gyanendra Singh
Gyanendra Singh
Flag of India image

ues Try catch block

Try

{
// Your code
}

Catch()
{
}
how are you reading your data
if its in a loop then
while (true)
{
   try
   {
       //processing code here
    }
    catch (Exception Ex)
    {
        //process the exception here
        continue;
     }
}
In your process code, add a try...catch block and append all exceptions to a string.
StringBuilder errors = new StringBuilder();
// begin of your process
while(...)
{
    try
    {
        // your code here
    }
    catch(Exception ex)
    {
        errors.AppendFormat("{0};", ex.Message);
    }
}
 
// read all errors using errors.ToString();

Open in new window

The trick with a try/catch block is that you jump all the way to the catch.  If you want to continue processing, a large try block around everything probably won't do what you want.  You need several try catch blocks, one wrapping each exception that could be thrown at a very fine level.
>>>If I encounter an error, the method stops. I would like to process the data in the file until the end, whatever error I encounter in the way.
That will be a big "NO NO". Whenever your application tells you there is an error, you better handle it first. The only exception is that the "error" is what you already expect and you are very sure that you can igore it without causing any problems.
Avatar of karakav
karakav

ASKER

Actually I have many errors already handled to that point that any other error should not be allowed to stop the execution. That's why I want to catch them apart and then examine them at a latter time. I found the solution of tiagoSalgado viable except that I don't see how I will recuperate the content of the StringBuilder since it is in a method wich returns other ting than String.
ASKER CERTIFIED SOLUTION
Avatar of tiagosalgado
tiagosalgado
Flag of Portugal image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of karakav

ASKER

Thanks a lot.