Nested Try and Catch blocks [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have nested try-catch blocks in a custom C# code for SharePoint. I want to execute the code in only one catch block (the inner one) when the code inside the inner try block throws an exception.
try
{
//do something
try
{
//do something if exception is thrown, don't go to parent catch
}
catch(Exception ex) {...}
}
catch(Exception ex)
{ .... }
I know I can use different types of exceptions but that's not what I am looking for.
Summary
If exception occurs, I don't want it to reach the parent catch in addition to the inner catch.

If you don't want to execute the outer exception in that case you should not throw the exception from the inner catch block.
try
{
//do something
try
{
//do something IF EXCEPTION HAPPENs don't Go to parent catch
}
catch(Exception ex)
{
// logging and don't use "throw" here.
}
}
catch(Exception ex)
{
// outer logging
}

The outer catch wouldn't fire if the inner catch handled the exception
If you want the outer catch to fire as well, you'd have to do:
try
{
//do something
try
{
//do something
}
catch(Exception ex)
{
// do some logging etc...
throw;
}
}
catch(Exception ex)
{
// now this will be triggered and you have
// the stack trace from the inner exception as well
}
Essentially, as you have the code there now, the outer catch will not be triggered from the inner try {} catch {}

Related

Try Catch to Handle Exception [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I am trying to update some documents in DocumentDb / CosmosDb, and if that fails, need to do something else, and then if that fails to log it out...
try {
do a thing w/ database
}
catch (DocumentClientException dce1) {
try {
do another, alternative thing w/ database
}
catch (DocumentClientException dce2) {
log to app insights.
}
}
I'm not sure about this, it seems clunky.. what do you guys think?
For additional bonus points, I need to do this quite frequently.. so something that I can farm off somewhere would be even better ;)
Personally I'd avoid intermixing exception flow with a functional logic flow. It can get brittle. Instead, convert the exception into a logical flag and use it in ordinary logic constructs.
So step 1 is catch the exception and set a variable or return value based on it, and wrap this in an independent method to mask the messiness from everyone else:
bool TryDoSomethingWithDataBase()
{
try
{
//Do thing that could fail
return true;
}
catch(SpecificException ex)
{
return false;
}
}
bool TryDoSomethingElseWithDataBase()
{
try
{
//Do thing that could fail
return true;
}
catch(SpecificException ex)
{
return false;
}
}
Step 2 is to write the logic as usual:
if (!TryDoSomethingWithDatabase())
{
if (!TryDoSomethingElseWithDatabase())
{
LogFatalError();
}
}
Or
var ok = TryDoSomethingWithDatabase();
if (ok) return;
ok = TryDoSomethingElseWithDatabase();
if (ok) return;
LogFatalError();
Why would your thing with the Database fail? You would be better coding for the conditionals you are aware of and expecting and do different things if you want to go into a different logic for processing the result.
Try catch will catch anything and everything, so if your connection to the db fails etc or if you are trying to read or insert malformed data etc.
Try catch does have various exceptions that you can investigate further and catch the specific exception you are interested in.. e.g.
try
//try something
catch (Exception ex)
{
if (ex is FormatException || ex is OverflowException)
{
//Do something specific;
return;
}
throw;
}
This is ok but if you say you'll have this over and over it's better to extract that logic and reuse it.
One way of doing this is to have a method that accept the first and section actions as parameters, for example:
public void TryThis(Action doFirst, Action doSecond)
{
try {
doFirst();
}
catch (DocumentClientException dce1) {
try {
doSecond();
}
catch (DocumentClientException dce2) {
log to app insights.
}
}
}
And then use it like so:
public void DoSomethig1()
{
...
}
public void DoSomething2()
{
...
}
TryThis(DoSomething1, DoSomething2)

Why does Resharper think that this catch clause is redundant? [duplicate]

This question already has answers here:
Why does resharper say 'Catch clause with single 'throw' statement is redundant'?
(6 answers)
Closed 6 years ago.
Resharper thinks the last catch clause is redundant. Why?
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
try
{
var response = (HttpWebResponse) request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var jsonResult = streamReader.ReadToEnd();
}
}
catch (WebException e)
{
Exception newEx;
if (e.Response != null)
{
using (var sr = new StreamReader(e.Response.GetResponseStream()))
{
newEx = new Exception(sr.ReadToEnd(), e);
}
}
else
{
newEx = new Exception(e.Message, e);
}
throw newEx;
}
catch (Exception ex) // Resharper thinks this clause is redundant
{
throw;
}
Because it is a default behavior - not caught exceptions will go further without need to rethrow them.
C# reference:
When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception. If the currently executing method does not contain such a catch block, the CLR looks at the method that called the current method, and so on up the call stack.
In your particular case if you will not rethrow exceptions, other then WebException clr will continue to unwind stack looking for next try-catch.
If you rethrow that exceptions, clr will continue to unwind stack looking for next try-catch too.
So, no difference.
Probably because your catch block isn't doing anything except rethrowing the same exception:
catch (Exception ex) // Resharper thinks this clause is redundant
{
throw;
}
You could proof it by adding some code in that catch block.

How to keep running a program if an exception occurs? [duplicate]

This question already has answers here:
Keep an Application Running even if an unhandled Exception occurs
(5 answers)
Closed 8 years ago.
I have an application that connect with two server. If it cannot connect with a server, an exception is thrown. I want the program to continue executing and instead try to connect to the other server. How can I do that?
Use a try catch block.
var serversToTry = new []{"Server1", "Server2"};
foreach (var server in serversToTry)
{
try{
//connect to server
return; //if you made it this far, connection succedded.
}
catch (Exception e)
{
//log e if you want
}
}
Just use the go to function try-catch:
try
{
//do something
}
catch(SpecificException ex)
{
}
catch(LessspecificException ex)
{
}
catch(EvenLessSpecificException ex)
{
}
catch(Exception ex)
{
//general exception
}
finally
{
//execute always!
}
Note, that you can use multiple catch statements to catch different exceptions. Use the most specific exceptions first and generalize from there on.
the finally statement is optional, but if you implement it, it will get called everytime, no matter if an exception occured or not.

Execution of multiple catch blocks [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
executing multiple catch blocks
Can multiple catch blocks be executed for a single try statement?How can we handle the catch blocks?Can we create try without catch block??
There can be multiple catch blocks (as said in other answers already), but only the one that first matches the exception type is executed. That means you need to order the catch blocks properly. For example:
try
{
}
catch (Exception exp1)
{
// Block 1
}
catch (IOException exp2)
{
// Block 2
}
Block 2 will never be executed, as block 1 catches every exception (all exception classes are derived from Exception).
try
{
}
catch (IOException exp1)
{
// Block 1
}
catch (Exception exp2)
{
// Block 2
}
In this example, block 2 will only be executed if the exception is not an IOException or derived from IOException. If an IOException is thrown, only block 1 will execute, block 2 will not.
You can have multiple catch blocks associated with a try block,but only a single catch block can ever handle your exception.
Yes you can have a try block without a catch,but it is mandatory to have a
finally block
Technically you can only hit one catch BUT you say:
Can multiple catch blocks be EXECUTED for a single try statement
Keyword being executed. So, you could try:
catch (Exception ex)
{
if (ex is MyException1||
ex is MyException2)
{
//do stuff
}
else
{
throw;
}
}
Yes you can have multiple catch blocks with try statement. You start with catching specific exceptions and then in the last block you may catch base Exception. Only one of the catch block will handle your exception.
You can have try block without a catch block. try/finally will do.
try
{
Console.Write("test");
}
catch (IOException ex)
{
}
catch (ArithmeticException ex)
{
}
catch (Exception ex)
{
}
try without catch
try
{
}
finally
{
}
1 Yes it's possible to have multiple catch, one catch for one specific exception
Sample
try
{
...
}
catch (FormatException)
{
....
}
catch (OverflowException)
{
...
}
2 You can have try instrction without catch
try
{
...
}
Finally
{
.....
}
Only one catch block will execute, and it will be the catch that closely matches the type of the Exception that was thrown.
You can't have a try by it self. You need a try catch (one or more catch block) or a try finally or a try catch finally
You can have any number of catch block for a single try..catch statement.
But please remeber one thing, that your
catch (Exception ex)
{
...
}
Should be the last catch block, since all exceptions inherits the the class Exception.
As for the second part of your question, you can do either
try
{
stuff...
}
catch(Exception ex){}
or
try
{
stuff...
}
finally{}
, but you can't do try by itself.

Try Catch handled at top of process

if I do this:
try
{
//code
}
catch (Exception)
{
throw;
}
Does the Exception go up with all its information?
The idea is to handle errors at the top of the app. There I'd execute some SQL sp to fill the admin's table so he's aware of exceptions.
I want to store Exception.Message and the source (method, function, whatever..) of the exception. But I don't know how to refer to "where" the exception happened. Is it Exception.Source? Exception.TargetSite?
Thanks.
The type of Exception will tell you what kind of exception it is (IndexOutOfRangeException, SqlException, etc) which you would react too accordingly:
try
{
//code
}
catch (SqlException ex)
{
// Handle code
}
catch (IndexOutOfRangeException ex)
{
// Handle code
}
catch (Exception ex)
{
// Handle code
}
As to where it is happening... you should be enclosing exception-prone areas with a try catch and not large code chunks. This way you will know where the exception derives from.
The Short answer is yes: just calling throw passes everthing regarding the exception up.
throw ex resets the stack trace (so your errors would appear to originate from HandleException)
throw doesn't - the original offender would be preserved.
(quoted from Mark Gravell)

Categories

Resources