Solved

silly try catch question

Posted on 2012-03-23
16
394 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 

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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
If you're a developer or IT admin, you’re probably tasked with managing multiple websites, servers, applications, and levels of security on a daily basis. While this can be extremely time consuming, it can also be frustrating when systems aren't wor…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

695 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