473,666 Members | 2,115 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1489
It laregely depends on how you have coded your site. You can have exceptions
caught in the Application_err or 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*@discussion s.microsoft.com wrote in message
news:A1******** *************** ***********@mic rosoft.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.Exceptio n, 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 OpenSqlConnecti on(string connectionStrin g)
{
using (SqlConnection connection = new SqlConnection(c onnectionString ))
{
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*@discussion s.microsoft.com wrote in message
news:A1******** *************** ***********@mic rosoft.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*@discussion s.microsoft.com wrote in message
news:A1******** *************** ***********@mic rosoft.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.Sq lException)
{
throw new MyCustomExcepti on("Houston, the database is experiencing
some issues." , ex);
}
catch (Exception ex)
{
throw new MyCustomExcepti on("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.Inn erException)
{
Response.Write (ex.InnerExcept ion.Message);
}
}
The reason you might write a MyCustomExcepti on ... 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 "presentati on", 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*@discussion s.microsoft.com wrote in message
news:A1******** *************** ***********@mic rosoft.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*@discussion s.microsoft.com wrote in message
news:A1******** *************** ***********@mic rosoft.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...f inally 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
3198
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 indeed also true for our language of choice, Python. Its file type allows some extraordinary convenient access like: for line in open("blah"): handle_line(line)
28
2240
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 changed -- people are still using a coding style, which I call pre-C++-Exception-Handling. Is this different in your experience? What is your experience regarding this subject? I think that a C++ IOstream lib, which is by standard free of exceptions...
9
2534
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 the way of CPU usage), compared to the "normal" practise returning values. How true is this? Will using using exception handling, in general, be much less efficient than returning values, or less efficient at all? Just curious...
6
746
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 there a way to list exactly which exceptions that are not handlet? (design time) I could of cause ... use catch (Exception e) {...} as the final catch ... but I would prefer to now the "landscape" before doing that ..
34
2220
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 ////////////////////////////////// Try { for ( ... ){// Code that might throw exception} }catch(...){} //////////////////////////////////////////////////////////////////////////
2
5865
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 the best thing to do: 1. Dont catch the exception in DAL and let it prop up to the Application level and the Global.Application_Error event log it to any source and show let ASP.NET show custom error page provided in Web.Config file. OR 2....
16
2537
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 method: // --- Create an Exception Handler for Thread Exceptions ---------------- Application.ThreadException += new ThreadExceptionEventHandler(OnThreadException);
5
3826
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 in the application log. The static method is overloaded, and supports passing exceptions and/or strings just like throwing an exception.The class will also fall back to the standard exception handling if something goes wrong in my class. As an...
35
3770
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 gets about 3 or so. It also gets very awkward in nested loops, where you want to check for normal loop processing in the loop condition, not errors. Yes, you could put some generic exit flag in the loop condition, but when you're simply done if...
35
3499
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, especially as programs get large. Most of the issues of exceptions are not specific to Python, but I sometimes feel that Python makes them more acute because of the free-n- easy manner in which it employs exceptions for its own uses and allows users...
0
8356
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8783
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8552
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8640
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6198
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5666
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4369
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2773
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1776
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.