473,385 Members | 1,396 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Correct way of handling exceptions?

VMI
What's the correct way of using try...catch in my web application? For
example, if I catch a connection error or something with the DB, how am I
supposed to bubble it up to the web interface?
Is there a correct way?

Thanks for the help.

Oct 16 '06 #1
6 1463
It laregely depends on how you have coded your site. You can have exceptions
caught in the Application_error and simply redirect a user.

If, instead, you think you can handle the error, you can set up a try ...
catch. If you cannot solve the error, the only reason to catch is to display
an error on the problem page. This is only useful, IMO, if you have some
bits working and others not. Otherwise, you are merely keeping the user on a
broken page.

In most cases, unless I am logging, I try ... finally and allow a bubble up
to the UI. Then, I just make sure the user has a nice error page, like
Orkut's "bad server, no cookie" error page.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA
http://gregorybeamer.spaces.live.com

*************************************************
Think outside of the box!
*************************************************
"VMI" <VM*@discussions.microsoft.comwrote in message
news:A1**********************************@microsof t.com...
What's the correct way of using try...catch in my web application? For
example, if I catch a connection error or something with the DB, how am I
supposed to bubble it up to the web interface?
Is there a correct way?

Thanks for the help.

Oct 17 '06 #2
A try/catch block simply gives you a chance to handle an exception in some
way. The exception can be rethrown, or handled in any other way you wish.
*How* you handle it depends largely upon what type of exception was thrown,
and what sort of recovery (if any) can be made. Now, as for type, every type
of exception *is* a type, and you can use multiple catch blocks, one for
each possible type of exception you anticipate, even one that catches
System.Exception, to catch any exceptions that are not caught by other catch
blocks. Of course, the more specific types should be caught first, so that
the catch-all catch block doesn't catch any of them before they get a chance
to.

For example, in your case, you might put in a catch block for a
SqlException:

private static void OpenSqlConnection(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
}
catch (SqlException sqlEx)
{
// do something about the connection error,
// such as informing the user
}
catch (Exception ex)
{
// do something else.
{
}
}

--
HTH,

Kevin Spencer
Microsoft MVP
Chicken Salad Shooter
http://unclechutney.blogspot.com

A man, a plan, a canal, a palindrome that has.. oh, never mind.

"VMI" <VM*@discussions.microsoft.comwrote in message
news:A1**********************************@microsof t.com...
What's the correct way of using try...catch in my web application? For
example, if I catch a connection error or something with the DB, how am I
supposed to bubble it up to the web interface?
Is there a correct way?

Thanks for the help.

Oct 17 '06 #3
Almost forgot. Here are a couple of good references:

http://msdn2.microsoft.com/en-us/lib...exception.aspx
http://msdn2.microsoft.com/en-us/lib...onnection.aspx

--
HTH,

Kevin Spencer
Microsoft MVP
Chicken Salad Shooter
http://unclechutney.blogspot.com

A man, a plan, a canal, a palindrome that has.. oh, never mind.

"VMI" <VM*@discussions.microsoft.comwrote in message
news:A1**********************************@microsof t.com...
What's the correct way of using try...catch in my web application? For
example, if I catch a connection error or something with the DB, how am I
supposed to bubble it up to the web interface?
Is there a correct way?

Thanks for the help.

Oct 17 '06 #4

VMI,

You actually don't have to catch everything in the lower levels.

try
{
}
finally
{
}

//no catch

Do a google search for "try catch finally Brad Abrams" and you'll find some
tidbits about this.

In a web environment, here is what I do.

In the DataLayer, I just write try/finally's

public class EmpData
{

public void UpdateEmployee(DataSet ds)
{
try
{
//code up and run some stored procedure
}
finally
{
//clean up resource use
}
}

}

In the BusinessLayer, I ~sometimes catch the exception, and create my own
"more friendlier" exception

try
{

}
catch (System.Data.SqlException)
{
throw new MyCustomException("Houston, the database is experiencing
some issues." , ex);
}
catch (Exception ex)
{
throw new MyCustomException("Houston, this is a friendly error
regarding having a problem." , ex);
}
Creating or subclassing your own Exception is not hard. I usually have a
constructor which takes another exception....


In the webpage, in the code behind .... I have this

try
{
''do something
}
catch (Exception ex)
{
//Maybe a response.write OR a direct to a common exception showing
page
Response.Write (ex.Message);
if(null!=ex.InnerException)
{
Response.Write (ex.InnerException.Message);
}
}
The reason you might write a MyCustomException ... is to push up a more
"friendlier" Message to the user.
Like, if the database fails on a constraint violation, you can intercept
that, and give a more "The age of the person violates a database constraint"
or something like that.

However, if Presentation layer means "presentation", perhaps you could catch
the exception there, and re-word it.
I prefer the biz layer.
I actually write many many more
try/finally

instead of

try
catch (Exception ex)
{
throw;
}
finally
{

}
If you're not going to do anything but catch it, then rethrow it, then don't
waste the effort. Just don't write in a "catch" in the try/finally

PS

If you do catch an exception remember

catch(Exception ex)
{
throw ex;//erases the StackTrace
}

VS

catch(Exception ex)
{
throw;//retains the StackTrace
}
You can test it, but the first one erases the StackTrace.
The second one retains the StackTrace.

That's a nice little nugget to be aware of.

PPS

The Exception Publishing Application Block is a nice add in.
I've written a custom publisher which
Writes out an error log
Sends an email.
Updates a database.

http://www.microsoft.com/downloads/d...B-8F22CA173E02

The built in , default functionality is to write to the EventLog.

The Enterprise Library has an updated version, but I still find the this
version of the EMAB useable.


"VMI" <VM*@discussions.microsoft.comwrote in message
news:A1**********************************@microsof t.com...
What's the correct way of using try...catch in my web application? For
example, if I catch a connection error or something with the DB, how am I
supposed to bubble it up to the web interface?
Is there a correct way?

Thanks for the help.

Oct 17 '06 #5
"VMI" <VM*@discussions.microsoft.comwrote in message
news:A1**********************************@microsof t.com...
Is there a correct way?
Yes there is - and it's up to you to decide what it is... :-)

In addition to the others' replies, I tend to have a rule that base classes
catch errors but don't handle them - they simply rethrow them so that's it
up to the the caller class to handle them and take appropriate action. E.g.
I have a database abstraction layer base class where the methods have lots
of try...catch...finally blocks looking specifically for SqlException errors
e.g. no connectivity, wrong password etc. If one of these errors occurs the
process stops and the error is rethrown so that the caller can process it.
Oct 17 '06 #6
i'm not actually one to comment, as I don't have any official training in
asp.net other than online resources, but I've been coding for some time
now...anyway, history aside, when I discovered the Try command in asp.net, i
found it most awesome. so i created an aspx page (errorpage.aspx) and
everytime I trapped a critical exception, i would redirect to the errorpage
with the type (either db, email, filesystem, etc.) and ex.message, the
errorpage.aspx would log the error in the eventlog (for adm's) and greet the
user with a friendly error and if the error was not email, would email the
adm that there was an error on the page.

--
The walls between art and engineering exist only in our minds
"VMI" wrote:
What's the correct way of using try...catch in my web application? For
example, if I catch a connection error or something with the DB, how am I
supposed to bubble it up to the web interface?
Is there a correct way?

Thanks for the help.
Oct 17 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Hans-Joachim Widmaier | last post by:
Hi all. Handling files is an extremely frequent task in programming, so most programming languages have an abstraction of the basic files offered by the underlying operating system. This is...
28
by: Frank Puck | last post by:
Meanwhile there are at least 8 years that compilers exist, which provide a working implementation of C++ Exception Handling. Has anything changed meanwhile? From my point of view nothing has...
9
by: C# Learner | last post by:
Some time ago, I remember reading a discussion about the strengths and weaknesses of exception handling. One of the weaknesses that was put forward was that exception handling is inefficient (in...
6
by: Jesper Ordrup Christensen | last post by:
Say I've created a piece of code that involves both sql, io and some number conversions. Being a responsible developer I have tried to catch all of the exceptions - but how can I be sure? Is...
34
by: rawCoder | last post by:
I have read that Exception Handling is expensive performance wise ( other than Throw ) , but exactly how ? Please consider the following example ... ////////////////// Code Block 1...
2
by: Rajeev Soni | last post by:
Hi, Considering the scenario for handling exceptions in Web Application where we have Presentation layer, Business layer and Data Access layer; if there any exception is occurred in DAL, what is...
16
by: Chuck Cobb | last post by:
I'm implementing a centralized exception handling routine using the Enterprise Library Exception Management Application Block. I trap all unhandled exceptions to one place using the following...
5
by: Bry | last post by:
I've created a class that offers an enhanced way of handling fatal exceptions. The class allows the user to optionaly submit a http based anonymous error report to myself, and also records details...
35
by: jeffc226 | last post by:
I'm interested in an idiom for handling errors in functions without using traditional nested ifs, because I think that can be very awkward and difficult to maintain, when the number of error checks...
35
by: eliben | last post by:
Python provides a quite good and feature-complete exception handling mechanism for its programmers. This is good. But exceptions, like any complex construct, are difficult to use correctly,...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.