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.
}
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.
What is difference between these types of catch, except that in first I can use e?
catch (Exception e)
{
//some code;
}
catch (Exception)
{
//some code;
}
catch
{
//some code;
}
try{
//do something
}catch{
//do something
}
This catch is executed, regardless of the exception.
try{
//do something
}catch (Exception) {
//do something
}
This catch is executed when a specific Exception is thrown
try{
//do something
}catch (Exception e) {
//do something
}
Same here, only that you have a reference to the Exception. That way, you have access to it.
Read more here.
Catch can catch different exception's types.
When you use the syntax catch(Exception) you are telling the compiler to write code that catches any kind of exceptions while, if you use a syntax like catch(InvalidOperationException), you are asking to catch a specific type of exception
To simplify things you can write catch without any type and this has the same meaning of catch(Exception)
try
{
// Uncomment this line to catch the generic exception
// throw new Exception("An exception occurred");
throw new InvalidOperationException("Operation x is not valid in this context");
}
// Comment the following lines to fall into the generic catch exception
catch (InvalidOperationException)
{
// But without the variable we cannot print out the message....
Console.WriteLine("An invalid operation has been catched");
}
catch (Exception)
{
Console.WriteLine("An exception raised");
}
You cannot use the syntax catch(Exception ex) in the same try catch where you don't specify the name of the variable for the same type of exception.
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// Syntax error: CS0160: A previous catch clause already catches ......
catch (Exception)
{
Console.WriteLine("An exception raised");
}
Strangely enough this doesn't result in a syntax error, but in a simple warning
catch(Exception)
{
....
}
// Warning CS1058: A previous catch clause already catches ......
catch
{
....
}
Of course you shouldn't catch exceptions that you are not prepared to handle. If you do it just to expose a message you risk the correct functionality of your program. Usually you catch only specific exceptions that you are know how to handle to allow your program to continue. The only reason that I could find to catch all exceptions is when you write down the exception data in some kind of log file and then throw again the exception.
catch(Exception ex)
{
Logger.Error("Unexpected exception", ex);
throw; // NEVER throw ex;
}
Remember that it is really never required to write throw ex because you loose the stack trace of the exception and make very difficult to track down the exact error point.
See: Best practices for catching and re-throwing .NET exceptions
If your code throws an exception, then the catch Block will be thrown and you have access to it over e.
catch (Exception e)
{
//some code;
}
If your code throws an exception, then the catch Block will be thrown indepented from the exception type and you don’t have access to it.
catch
{
//some code;
}
If your code throws an exception, then the catch Block will be thrown depending from the exception type and you don’t have access to it.
catch (Exception)
{
//some code;
}
Instead of Exception you should use a more specific exception type!
let's check
in this code you can write e.Message for check Catch Message
catch (Exception e)
{
Console.WriteLine("Error Message is : " + e.Message);
}
but in this you just skip From Exception (All Exceptions) and you can add more Exceptions
catch (sqlExcetion)
{
//if your code have sqlEsception Get here
}
catch (Exception)
{
//if your code have any Exception Get here
}
and in this code you can create one catch and all catch go this
catch
{
//all catch get here
}
The minor difference between:
try{
//do something
}catch (Exception) {
//do something
}
and
try{
//do something
}catch (Exception e) {
//do something
}
is: (the second one will give)
The variable 'e' is declared but never used
Also, if the code is like this:
catch(Exception e) { throw e; }
the original stacktrace is gone. So, you have to do: catch(Exception e) { throw; }
to see the original stacktrace.
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.
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.
If I have some code inside a big try catch which eventually catches an OracleException and a general Exception then I can't throw any custom exception inside the try catch can I, as it gets caught by the general Exception.
What am I supposed to do in this instance?
Thanks
try
{
// some code
if(a==b)
{
throw new MyCustomException(ex);
}
}
catch(OracleException ex)
{
...
}
catch(Exception ex)
{
...
}
Do you mean that you want to throw a custom exception that isn't caught by the catch-all Exception block?
If this is the case, then try this:
try
{
throw new MyCustomException();
}
catch (OracleException ex)
{
// Handle me...
}
catch (MyCustomException)
{
// Important: NOT `throw ex` (to preserve the stack trace)
throw;
}
catch (Exception ex)
{
// Handle me...
}
Any exception of type MyCustomException will be caught by the second catch (rather than by the 3rd catch) and then rethrown.
Note that it's generally bad practice to do catch (Exception) - this is a good example of why. I definitely suggest that rather than doing the above, you simply refactor so that you are no longer catching Exception, which would be a far neater solution.
check this:
try
{
...
}
catch()
{
throw new Execption("I'M A NEW EXCEPTION")
}
finally
{
...
}
Can't you simply add a catch clause with your custom exception?
try
{
//Lots of code
}
catch (OracleException)
{
}
catch (MyCustomException)
{
}
catch (Exception)
{
}
Try this
catch(OracleException ex)
{
throw new MyCustomException(
"MyCustomEX error: Unable to ......", ex);
}