Solved

silly try catch question

Posted on 2012-03-23
16
389 Views
Last Modified: 2012-03-27
Hi,

Stupid question I know but in my function below, where would the standard place to put the try catch be?

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            using (var db = new PublicUnitOfWork())
            {
                DisplayPageCMS(litPageTitle, litMetaKeywords, litMetaDescription, litBodyText, db, Common.CMSPages.Homepage);
            }
        }
    }

Open in new window

0
Comment
Question by:scm0sml
  • 8
  • 4
  • 4
16 Comments
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 37758679
Which function(s) has the potential to throw an exception?
0
 

Author Comment

by:scm0sml
ID: 37758684
well displaypagecms but what if there was an error in the construction of the unit of work for some reason....?

Should it be around the unit of work?
0
 
LVL 20

Expert Comment

by:BuggyCoder
ID: 37759039
well when you use using keyword the statement is automatically wrapped in try/finally block.
So Any errors will be caught and suppressed.

Ideally the statements used in using are the one's whose IDisposable implementation of Dispose is provided.

So if you want to catch exceptions and your unit of work doesn't implement Dipsose(), then its better to write the code like this:-

try
{
var db = new PublicUnitOfWork();
DisplayPageCMS(litPageTitle, litMetaKeywords, litMetaDescription, litBodyText, db, Common.CMSPages.Homepage);
}
catch(DisplayPageException ex)
{
}
catch(UnitOfWorkException ex)
{
}
catch(Exception ex)
{
}

Open in new window


Here catch blocks are placed in the order of most specific to least specific exception type.
Assuming DiplayPageException and UnitOfWorkException are custom exception.
0
 

Author Comment

by:scm0sml
ID: 37759094
i have a dispose function but it isnt doing anything at present...

stupid question but what should i be putting in there and how does it relate to error handling??
0
 
LVL 20

Expert Comment

by:BuggyCoder
ID: 37759175
if you have any native resource to free, you can do that.
Something like a database connection or an existing transaction, a file handle etc.
Something that you want your application to take control of disposing....

It has nothing to do with error handling, its just when you use using block, if the object created inside it is implementing IDisposable, the dispose will be called so that the resources that are to be disposed can be disposed.
0
 

Author Comment

by:scm0sml
ID: 37759184
So this is inside the unit of work:
public class PublicUnitOfWork: IPublicUnitOfWork,IDisposable
{
    readonly VirtuTypeEntities _context;

    public PublicUnitOfWork()
    {
        _context = new VirtuTypeEntities();
    }

    public void Dispose()
    {
        
    }

Open in new window


So I want to dispose of my _context, correct?
0
 
LVL 20

Expert Comment

by:BuggyCoder
ID: 37759196
it looks like you are using EF, you can do something like _context.Dispose() if it offers Dispose.
If not there is not need to derive from IDisposable.
0
 

Author Comment

by:scm0sml
ID: 37759200
it offers dispose yeah so it what I will do.

Thanks for your help!
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

Author Comment

by:scm0sml
ID: 37759208
Sorry one thing, if I want to handle an error that occurs within my using block.....

How would I do this....?
0
 

Author Comment

by:scm0sml
ID: 37759212
I'm not sure if that was actually answered or not...?
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 37759220
@BuggyCoder
well when you use using keyword the statement is automatically wrapped in try/finally block.
So Any errors will be caught and suppressed.
That is not correct. The error is caught, but it is not suppressed. It is bubbled up to higher layers until an equivalent catch is found or the program crashes (meaning no catch was found). A finally without a catch is NOT handling an exception.

@scm0sml
well displaypagecms but what if there was an error in the construction of the unit of work for some reason....?
I have seen differing opinions on this, but I believe MS' official recommendation is that constructors not throw exceptions. Generally speaking, your constructor should be simply setting up the state of your object, so you wouldn't really expect field assignments to raise exceptions. The discrepancy comes in, however, when you are getting values from external sources which you do not control (e.g. you read a field's value from the filesystem).
0
 

Author Comment

by:scm0sml
ID: 37759226
ok kaufmend so are we saying that if I want to handle an error that occur specifically within my using I have a try catch of its own?
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 37759227
When I say "the error is caught," I am not implying that an implicit catch is in the works. Rather I am saying that execution within the try does not continue at the line which raised the exception.
0
 
LVL 20

Accepted Solution

by:
BuggyCoder earned 250 total points
ID: 37759230
Don't use using block, use try/catch/finally and dispose of object in finally.
0
 
LVL 74

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 250 total points
ID: 37759246
You should handle errors at the place where it makes sense to handle errors. As I mentioned above, exceptions are "bubbled up" the stack until a compatible catch clause is found. If you were writing an ASP.NET application which queried a database for a particular user, then it might not make sense to wrap the database call itself in a try/catch--if you can't query the required data, then the user can't use the application. In this case, you might let the exception bubble up to the top layer where you redirect the user to an error page rather than give them a second attempt at displaying the page. On the other hand, if you are taking in numeric values from a user via a TextBox, and they enter in an alphabetic string, wrapping the code which does arithmetic against the TextBox's value makes sense, because you want to alert the user that he didn't enter appropriate data. In this instance, giving the user a chance to correct the data is a logical way to handle the exception.
0
 

Author Comment

by:scm0sml
ID: 37759271
OK thanks guys.

Been doing a bit of reading at the same time as this and I think I'll go with the try catch finally!!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now