Solved

silly try catch question

Posted on 2012-03-23
16
391 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 75

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
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 

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
 

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 75

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 75

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 75

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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

776 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