How to resume second method after first method throws an exception C# - c#

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.

Related

Proper usage of finally clause in try/catch block

I'm trying to figure out the "best" way execute a (close) statement in my sql data access layer methods.
I was wondering which of the two ways is considered more correct (thanks):
Option #1
public void dbOperation( ... )
{
try
{
_cmd.Open();
_cmd.Execute();
}
catch (Exception ex)
{
throw ex;
}
finally
{
_cmd.Close()
}
}
Option #2
public void dbOperation( ... )
{
try
{
_cmd.Open();
_cmd.Execute();
}
catch (Exception ex)
{
_cmd.Close()
throw ex;
}
_cmd.Close();
}
Neither is correct. You shouldn't have a catch clause just to re-throw the exception again, clearing out its stack trace, and doing nothing productive, which is what your first option does.
You should just be closing in the finally:
try
{
_cmd.Open();
_cmd.Execute();
}
finally
{
_cmd.Close()
}
Your second snippet has the same problem with it, since you're improperly re-throwing the exception.
The best option would be to use a using, which is just a syntactic sugar for a try/finally without a catch:
using(var command = ...)
{
command.Open();
command.Execute();
}
This has the added benefit of also ensuring that the scope of the command is exactly the same as when it's valid to use it. A try/finally block requires the command to be a valid identifier after it has been disposed of.
Option #1 is the only correct one of the two. In fact, you can get the equivalent of option #1 using less code:
try
{
_cmd.Open();
_cmd.Execute();
}
finally
{
_cmd.Close()
}
If an exception is thrown, there's no need to have a catch block to just re-throw it. If you want to do something in the catch block, such as logging the exception, be sure to do this:
try
{
_cmd.Open();
_cmd.Execute();
}
catch (Exception ex)
{
logException(ex);
throw; //Just say throw, not throw ex, to preserve the original stack trace
}
finally
{
_cmd.Close()
}
Option #1. If you use option2 you won't execute cmd.close unless it throws an exception

C# - Exception handling from within finally clause

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.
}

Catch InvalidOperationException with empty structure

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.

Calling methods which might throw inside catch

Let us say we have an external server which we use (e.g.-telephony station, etc.). Also we have the next code:
try
{
externalService.CreateCall(callParams);
}
catch (Exception ex)
{
_log.Error("Unexpected exception when trying execute an external code.", ex);
_callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
throw;
}
Theoretically UpdateCallState could throw but we would hide this exception using that code and would treat only exceptions generated by CreateCall in a right way.
The question is, what is the right pattern for these situations so that we treat all the exceptions correctly?
You can always nest another try..catch inside the first catch and deal with it appropriately.
try
{
externalService.CreateCall(callParams);
}
catch (Exception ex)
{
_log.Error("Unexpected exception when trying execute an external code.", ex);
try
{
_callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
}
catch(Exception updateEx)
{
// do something here, don't just swallow the exception
}
throw; // this still rethrows the original exception
}
Break it up. Something like
if !TryCreateExternalCall(callParams)
{
_log.Error("Unexpected exception when trying execute an external code.", ex);
_callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
}
else
{
throw new ExternalServiceException(???);
}
TryCreateExternalCall should of course log the exception and stacktrace, before it swallows and returns false.
It is not a good practice to throw exception in Catch block.
The try, Catch suggest that
try
{
//make some changes. If something goes wrong go to Catch.
}
Catch(exception)
{
//I will clean the mess. Rollback the changes.
}
Catch the exception, only if you can handle the exception. Else bubble it up let the caller decide on what to do with the exception.
You should catch the most specific exception first, followed by the most general exceptions.
try
{
externalService.CreateCall(callParams);
}
catch (CreateCallExceptionType ccEx)
{
_callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
}
catch (Exception ex)
{
//do something
}
And then you could handle the UpdateCallState exception within the method.

Why multiple try..catch block not working properly in same method in c# 2.0?

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();

Categories