• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 239
  • Last Modified:

is it OK to do a nested try/catch?


I am getting this error, "Index was outside the bounds of the array"
So I can guess that this is coming out ofthe array/list/ in my case, I think it is coming from the listview.

There is several sections of the code and one try/catch to capture an exception.

Is it ok to insert more try/catch into those small sections of the code to where exactly the error is coming from?
I still this overall try/catch where there is one function from the final{}.

4 Solutions
James AtkinSenior Principle Software EngineerCommented:
Yep, this is always very good practice...
It helps to control the program flow when unknown situations occur..
Hope this helps,
AndyAinscowFreelance programmer / ConsultantCommented:
Yes you can do that, in fact I would say it is good practice.  Gives you tighter control on possible sources of error and what to do in that case.
i prefer not to do that because it makes the code more complex by having nested try catches, catching maximum number of exceptions explicitly withing the same try catch would be better. Anyway, here is a good argument on this. See if you get your answer here.

There are many ways to code and deal with exceptions. I agree with the others that nesting handlers can often be the best approach, as it allows you to know exactly what failed.

It never hurts to proactively prevent exceptions or to manually raise one when you detect that an exception WOULD occur.

For instance, I often add a check before accessing a property or method on an object variable to ensure that the obj is set. Otherwise, you get an unhelpful message like "object not set". I will first check it and if it's null either throw an exception or I'll use a debug.assert.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now