i am trying to handle exception and save that exception in database
Function1()
{
try
{
for(int i=0;i<dt.rows.count;i++)
{
Function2();
}
}
catch(exception ex)
{
saveInDB(ex.message.tostring(),id);
}
}
Function2()
{
try
{
function3()
}
catch(exception ex)
{
throw ex;
}
}
Function3()
{
try
{
function4()
}
catch(exception ex)
{
throw ex;
}
}
Function4()
{
try
{
code;
}
catch(exception ex)
{
throw ex;
}
}
suppose i got a exception in method4 then it will throw it to function3->Function2->function1 and then function1 will write exception in database.
but after writing exception in DB i want to continue for loop.
so how should i do?
but after writing exception in DB i want to continue for loop
That is only possible by putting an (extra) try/catch inside the for loop. You should do so only if the next round of the loop is independent and you are certain there is no harm done to your system.
Ask yourself: After an unknown error, do I still dare to write business-data to the database?
Notice that your code is in violation of some best-practices:
throw ex; resets the stack-trace. Replace it with throw;
when the catch blocks in function2 - function4 don't do anything with the exceptions, remove the try/catch altogether.
You can put your try-catch into the for loop's body:
Function1()
{
for(int i=0;i<dt.rows.count;i++)
{
try
{
Function2();
}
catch(Exception ex)
{
saveInDB(ex.message.tostring(),id);
}
}
}
Keep in mind, however, that IO such as saving to DB may be pretty unreliable (and slow). This in turn might lead to further exception being thrown in your catch, which will tear down your loop.
Therefore it might be better to store all thrown exception in a data structure and dump them to the DB at once. This way the loop runs for each and every row.
Function1()
{
var errors = new LinkedList<Exception>();
for(int i=0;i<dt.rows.count;i++)
{
try
{
Function2();
}
catch(Exception ex)
{
errors.AddLast(ex);
}
}
if(errors.Count > 0)
{
// now you got all exception in errors and can dump
// them in one block
}
}
As long as any try-catch block throws the exception, the program cannot continue.
If you want your program to be continue after exception handling, my suggestion would be not to use:
throw ex;
If you need to continue looping after an exception within the loop, you need to add a try/catch block within the loop as below;
try{
for(int i=0; i<10; i++){
try{
//do your work here
}
catch (Exception e){
//write to db here and then it will continue in the for loop
}
}
//rest of the code
}
catch (Exception ex){
//write to db
}
Related
While looking on C# try catch tutorial, I got following question. My sample code as follows,
Inside mainMethod() , I need to call three separate methods. Inside testMethodOne(), I need to handle exception as. If testMethodOne() throws exception, without executing testMethodTwo(dt), mainMethod() throwing exception. I need to call testMethodTwo(dt); and testMethodThreee(dt); if testMethodOne() throws exception, how can I do it.
public void MainMethod(data dt){
try{
testMethodOne(dt);
testMethodTwo(dt);
testMethodThreee(dt);
}catch(Exception ex){
throw ex;
}
}
public void testMethodOne(dt){
try
{
// Block of code to try
}
catch (Exception e)
{
// Block of code to handle errors
}
}
I understood your question as follows (but I might be wrong, your questions is not very clear):
Even if one of your testMethods throws an exception, you still want to continue in the normal program flow with the other methods. If at least one of the method failed, mainMethod could then report this as AggregateException.
public void MainMethod(data dt)
{
var exceptions = new List<Exception>();
try
{
testMethodOne(dt);
}
catch (Exception ex)
{
exceptions.Add(ex);
}
try
{
testMethodTwo(dt);
}
catch (Exception ex)
{
exceptions.Add(ex);
}
try
{
testMethodThreee(dt);
}
catch (Exception ex)
{
exceptions.Add(ex);
}
if (exceptions.Count > 0)
{
throw new AggregateException(exceptions);
}
}
It seems as if you want exceptions to alter the flow of your main method without breaking everything. One easy method is to make each 'testmethod' return a boolean.
public bool testMethodOne(dt){
try
{
// Block of code to try
return true;
}
catch (Exception e)
{
// Block of code to handle errors
return false;
}
}
Then in your main code you can go
if(!testMethodOne(dt))
if(!testMethodTwo(dt))
if(!testMethodThree(dt))
//log that all methods failed
The above snippet would try each method until it finds one that succeeds. If that's not the behaviour you are looking for can you reword your question to make it clearer? If you want the opposite to happen just get rid of the ! and it will go until one fails. Alternatively you could put a throw in your catch statement in each of the testMethods, and that would stop execution once one is reached as well.
I have a method calling combo as below:
Void MainMethod()
{
try
{
for(i = 0; i < 10; i++)
{
Childmethod_1();
}
}
catch(Exception ex)
{
throw ex;
}
}
Childmethod_1()
{
try
{
Childmethod_2();
}
catch(Exception ex)
{
Report(ex);
}
}
Childmethod_2()
{
try
{
[Block of Code]
}
catch(Exception ex)
{
throw ex;
}
}
Report(ex) in the Childmethod_1() is used to log the exception details into Database. If there is an exception occures in the Childmethod_2() whenever 'i' in the MainMethod(): For Loop is 4, will this exception block the rest 6 from the action?
The throw from Childmethod_2 will be caught by the catch from Childmethod_1 and logged to DB too. That catch block does not throw it again, so the exception will not be seen in your main loop, which will not be interrupted.
By the way,
catch(ex)
{
throw ex;
}
isn't only bad practice, it's completely useless. Why not just let the exception happen? Furthermore, the exception sent will not be complete, you'll lose the stack trace. If you really wish to do so, just throw like that:
catch(ex)
{
throw;
}
The answer to your question depends on implementation of Report(ex) method. If it doesn't rethrow the exception, but only stored exception data into the DB, then all iterations of your loop will be executed regardless exceptions occurred. In this case you can simplify your code (look below). Note that in this case you should make sure that Report(ex) method can't throw other exceptions (for example accessing to the database).
void MainMethod()
{
for(i = 0; i < 10; i++)
{
Childmethod_1();
}
}
Childmethod_1()
{
try
{
[Block of Code]
}
catch(Exception ex)
{
Report(ex);
}
}
On the other hand if Report(ex) rethrows exception after storing data into the DB, then the exception will be caught in the catch block of MainMethod and other iterations will not be executed. In this case you can't omit the try-catch block in MainMethod. However ChildMethod_2 is still redundant.
The title is a bit misleading but the issue seems very straight-forward to me. I have try-catch-finally block. I want to execute the code in the finally block only if an exception was thrown from the try block. The structure of the code right now is:
try
{
//Do some stuff
}
catch (Exception ex)
{
//Handle the exception
}
finally
{
//execute the code only if exception was thrown.
}
Right now the only solution I can think of is setting a flag like:
try
{
bool IsExceptionThrown = false;
//Do some stuff
}
catch (Exception ex)
{
IsExceptionThrown = true;
//Handle the exception
}
finally
{
if (IsExceptionThrown == true)
{
//execute the code only if exception was thrown.
}
}
Not that I see something bad in this but wonder if there is another(better) approach to check if there's a thrown exception?
What about something like:
try
{
// Do some stuff
}
catch (Exception ex)
{
// Handle the exception
// Execute the code only if exception was thrown.
}
finally
{
// This code will always be executed
}
That's what Catch block are made for!
Don't use finally for this. It is intended for code that should always execute.
What exactly is the difference, in terms of when to execute, between
//Handle the exception
and
//execute the code only if exception was thrown.
I can't see any.
You don't need finally after all:
try
{
//Do some stuff
}
catch (Exception ex)
{
//Handle the exception
//execute the code only if exception was thrown.
}
The Finally part of a Try / Catch statement is always fired regardless of whether any exceptions have been found. I would recommend you don't use it in this scenario.
try
{
// Perform Task
}
catch (Exception x)
{
//Handle the exception error.
}
Finally
{
// Will Always Execute.
}
I am trying to catch the InvalidOperationException that can sometimes occur when declaring variables. The following code doesn't work however. Probably because I don't really know how you catch an exception.
public override void Download()
{
try
{
var t = (ForumThread)Globals.Db.Thread.Get(_extIdForumThread, _idF);
try
{
throw new InvalidOperationException();
}
catch (InvalidOperationException exception)
{
return;
}
catch (Exception exception)
{
throw;
}
}
}
Any help at all would be very appreciated.
You don't need to throw the exception yourself. Just have:
try
{
var t = (ForumThread)Globals.Db.Thread.Get(_extIdForumThread, _idF);
}
catch (InvalidOperationException exception)
{
// Error logging, post processing etc.
return;
}
You shouldn't really be catching the general exception either unless you have a really good reason to - i.e. your application cannot crash, but if you do you need to be able to recover from it.
I am doing this in the Form_Load() event of a desktop application
string strDay = DateTime.Now.DayOfWeek.ToString().ToUpper();
try
{
fnBirthDayReminder();
}
catch (Exception ex)
{
}
try
{
if (strDay == "SUNDAY" || strDay == "TUESDAY" || strDay == "THURSDAY")
{
fnAwaitingLeaveApplicationReminder();
}
}
catch (Exception ex)
{
}
try
{
fnLeavePlanRemainder();
}
catch (Exception ex)
{
}
try
{
fnContractExpiryRemainder();
}
catch (Exception ex)
{
}
Application.Exit();
But the application exists just after the execution of the first try..catch block. Even if I place BreakPoint on following try..catch's, these breakpoints were not hit. I am really confused about such mysterious behavior. Please help !
For you all,
"if one method throws an exception, the other methods will not run." this is the main reason I am using separate try..catch blocks. So that, even if a function gives an exception, the next can execute.
Edit2
Can you suggest me a nice approach other than I am using here to execute the next function even if an exception occurred during the first function. The way some of you are suggesting (calling all the functions in a single try block with multiple catch blocks) will not do, that's for sure. I am thinking about recoding the methods without spending more time.
Have you tried putting a breakpoint in the first catch block, and examining the exception message / stack trace? I've observed sometimes that the application can exit for certain types of exception, e.g. stackoverflow, rather than the expected behaviour.
try
{
fnBirthDayReminder();
}
catch (Exception ex)
{
Debugger.Break();
}
Finally, your methods shouldn't throw under normal circumstances. Try to find out why they are and remove the bugs.
Put a breakpoint on Application.Exit(); and watch is it hit after throwing an exception or not.
If breakpoint not hit then your solution is clear. In this case your code throwing a ThreadException or UnhandedException that force your program to close unexpectedly.
You can catch these exception by doing something like this in your Program.cs to avoid your app close unexpectedly:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
try
{
Application.Run(new Form1());
}
catch (Exception e)
{
HandleException(e);
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
HandleException(e.Exception);
}
static void HandleException(Exception ex)
{
//Do Something
}
Using such a code is not recommended. Try to use one try block and catch the exceptions in multiple catch blocks.
try
{
fnBirthDayReminder();
fnLeavePlanRemainder();
fnContractExpiryRemainder();
//...
}
catch(IOException ex)
{
//do something
}
//catch(...)
catch(Exception ex)
{
//do something
}
PS: in this sample if one method throws an exception, the other methods will not run.
PS2: The order of catch blocks changed. (Thanks to #ChrisF)
Pretty sure you need a finally in there as a try can have multiple catches, but not multiple "trys" within the context of the function.
try { myfunc(); }
catch(Exception ex) { doSomething(); }
finally {}
//time for next try
Indeed, the standard way of using try-catch block is to use multiple catch block with one try block .....
try
{
fnBirthDayReminder();
if (strDay == "SUNDAY" || strDay == "TUESDAY" || strDay == "THURSDAY")
{
fnAwaitingLeaveApplicationReminder();
}
fnLeavePlanRemainder();
fnContractExpiryRemainder();
}
catch (Exception ex)
{
}
Application.Exit();