Using Exceptions

Hi,

I've read that exceptions should only be used to catch exceptional occurences because they're slow.
However, is this true also for just using a 'finally' block.
If there's no exception thrown or caught, is using a 'finally' block a performance hit?
Cheers,
WT.

Web dev - spending forever achieving nothing.
0
WhatThe12
6/21/2004 9:58:45 AM
asp.net.getting-started 91979 articles. 3 followers. Follow

5 Replies
306 Views

Similar Articles

[PageSpeed] 36

You can't use a Finally block without a matching Try block. And the performance hit occurs before the Try/Catch code is executed. It is related to how .NET packages up code that is within a Try/Catch block, before its execution.

You've read that Try/Catch exception blocks should only be used to catch exceptional circumstances. This is largely due to the performance hit you've read about. But it also affects some threading issues.
The idea is that you only ever use a Try/Catch exception block where you can't first perform your own tests.
For example, say you want to retrieve an object from a session variable, and then work with it. The following is dummy code. I've left out casting just to keep it looking simple.
    currentUser = session["storedUser"];

MessageLabel.Text = "Hello, " + currentUser.Name;
This will cause an exception if the object was not actually within session. But because it may give rise to an exception does not mean we must wrap it in a Try/Catch block.
Rather, what we must do is run our own test first, to prevent the possibility of the exception.
    currentUser = session["storedUser"];

if (currentUser != null)
{
MessageLabel.Text = "Welcome back, " + currentUser.Name;
}
else
{
MessageLabel.Text = "Hello, visitor.";
}

In the vast majority of cases where an exception might occur, we can completely avoid it by running a test or two first.
However, in some circumstances, we cannot first run a test. The classic example of this is querying a database. If the database is unavailable, then an exception will occur. Yet we cannot test for the availability of the database before we query it. Hence, we must use a Try/Catch block.
But for 99% of exceptions, a preceeding test would have avoided it. So, Try/Catch blocks really should be left for the exceptional 1% of cases.
Does that help?

Alister
0
SomeNewKid
6/21/2004 10:31:32 AM
Yes, thankyou.


Try
{
... do database stuff
}
catch
{
}
finally
{
... close db connection
}

One always needs to close a db connection. If one only closes it in a finally block, is this more or less efficient that closing it within the try block and leaving out the finally block altogether?
Cheers,
WT.
Web dev - spending forever achieving nothing.
0
WhatThe12
6/21/2004 11:31:30 AM
I don't think the Try/Catch block is any less performant if it has a Finally block, too.

The idea is to use the Finally block to include code that must be executed whether the Try code works or fails. A database connection must be closed if is opened.
Putting the .Close() inside the Try block would mean it would not be executed if the Try block fails. If a line of code inside a Try block causes an exception, no more lines of code within the Try block will be executed. That Try block ceases execution. Control jumps straight to the first appropriate Catch block, and then jumps to the Finally block. Hence, if the .Close() were anywhere else except the Finally block, it may not be executed. So, we put it in the Finally block, to ensure that it is executed.
Does that help?

Alister
0
SomeNewKid
6/21/2004 12:34:46 PM
Yes. 

But if you put the .Close in the try block as well as the catch block, you could always check whether the db connection needs closing in the catch block.
Of course, if the finally block doesn't add the same kind of performance hit that adding a try/catch block does in the first place then its obviously better to only have .Close in the finally block.
Web dev - spending forever achieving nothing.
0
WhatThe12
6/21/2004 1:56:20 PM
I was wondering whether you'd ask me about putting the .Close command in the catch blocks.

The reason we don't, is simply to avoid duplication of code, which should always be avoided. Say we had a more extensive Try/Catch block (and I'm using fake exceptions here):

try
{
username = MyDatabaseConnection.ExecuteCommand( "SELECT name FROM users WHERE id=" + userid );
MyDatabaseConnection.Close();
}
catch( DatabaseMissingException e )
{
Log.Error( "Database was missing.", e );
MyDatabaseConnection.Close();
}
catch( DatabaseInvalidTableException e )
{
Log.Error( "Database table was missing.", e );
MyDatabaseConnection.Close();
}
catch( DatabaseInvalidFieldException e )
{
Log.Error( "Database field was missing.", e );
MyDatabaseConnection.Close();
}
catch( Exception e )
{
Log.Error( "Something went wrong.", e );
MyDatabaseConnection.Close();
}
I'm sure you're seeing where I'm going with this. That is, it is the purpose of the Finally block to hold code that must be executed regardless of the success or failure of the Try code.
So, instead of duplicating the DataBaseConnection.Close five times, we put it into the Finally block:
    try

{
username = MyDatabaseConnection.ExecuteCommand( "SELECT name FROM users WHERE id=" + userid );
}
catch( DatabaseMissingException e )
{
Log.Error( "Database was missing.", e );
}
catch( DatabaseInvalidTableException )
{
Log.Error( "Database table was missing.", e );
}
catch( Exception e )
{
Log.Error( "Something went wrong.", e );
}
finally
{
MyDatabaseConnection.Close();
}

Ahh, much cleaner.
Alister
0
SomeNewKid
6/21/2004 8:00:08 PM
Reply:

Similar Artilces:

How to get new web app to use .NET 2.0 on Win2K server using .NET 1.1 as default framework?
I have .net framework1.1 and 2.0 on our server running win2K. i have existing applications that uses asp.net 1.1, i also have a new app that use ASP.net 2.0.  how can i set my new .NET 2.0 app to point to asp.net 2.0 without messing up my existing .NET 1.1 apps? To specify the ASP .Net version fro a web application, do the followingIn IIS Manager select the web application -> Properties -> ASP.Net TabSelect  ASP.Net version you want to use for the applicationRegards,PrashantDont forget to click "Mark as Answer" on the post that helped you. But I am running Win2K...

Sending SMS using vb.net or C#.net using vb.net or c#.net
Hi  My requirement is I hav one csv file with these fields id,mobilenum,messgae,status.intiallu staus is 0. once i read the all fileds and take that mobile number.using tat mobile number  i need to send sms .after sending sms i shuld change status as 1 How to send sms thru coding (please dont provide any links.if it is provide also please give working links becox i checked codeproject .i didnt get any nice link. and also provide the how to update the status field im csv file   Thank ssandhya   To send SMS, you need some third party SMS providers. if you consul...

Getting Start With .net
hi i'm intersted to learn asp.net (vb or delphi) . i programming with delphi6 but i'd like to tp know something about programming in internet specially with .net . i hear about microsoft.net with delphi 7 that i can programming with delphi in .net .... is it right ? what 's our opinian about it ? and better to learn Vb.Net or continu with delphi(or delphi.net) thanks. Ali Darabian I think there is some support for Delphi in .Net. However, you will find much more support from the user community if you choose a more popular language such as VB.Net or C#. Since your al...

how to get start with .NET
the net help people installed  to my desktop 1-microsoft visual studio .NET enterprise developer 2003 2-microsoft .NET framework 1.1 what else do i need ...???  and how can i try with some simple code in VS.Net and run it to see wat happen...????? please help If you want to develope web applications, then you'll also need IIS on your PC.  That'll require XP-Professional or Windows 2000/2003, but XP-Home edition won't allow IIS installation. As for how to get started, you can search the web for some tutorials or buy a good book on VS.  The topic is way too vast to...

used a c#.net to vb.net converter and am now getting a syntax error.
ok I used a cool utility at http://www.kamalpatel.net/ConvertCSharp2VB.aspx to convert some c#.net to vb.net and it spit out a bunch of code which almost works but I am getting a syntax error on this line Imports (StreamReader sr = Shadows Function)() As StreamReader(objResponse.GetResponseStream()) I tried it that way and also like Imports (StreamReader sr = Shadows Function)() As StreamReader(objResponse.GetResponseStream()) but either way gave the same error Compiler Error Message: BC30035: Syntax error. Source Error: Line 26: Line ...

where can i get a complete tutorial that will get me seriously started on using the objectdatasource effectively
It looks like using the objectdatasource is the way to go. will some one point to a tutorial that will get me seriously started on using the objectdatasource effectively.--------------------------------------------------No Project Too Eazy.-------------------------------------------------- http://www.asp.net/learn/dataaccess/default.aspx?tabid=63Orhttp://www.imar.spaanjaars.com/QuickDocId.aspx?quickdoc=416 First one uses typed datasets, second one uses custom business objects.  Both excellent tutorials. Regards Mike [MVP - ASP/ASP.NET]My site...

Keep getting..."Unable to get project file from server",when using vs.net
When trying to open any existing asp.net project in Visual Studio it keeps giving me the message above. It is also throwing an error when I create the project in the first place, it happens when a dos window is opened, the text in the dos window is running "Common Language Runtime Minidump Utility version 1.0.3705.0" and then VS craps out says there was an error and shuts down. I've re-installed the .net components and framework with no avail, and FrontPage extensions etc.. are all installed. I'm running XP professional and have installed IIS 5.1. This is driving me fec...

using relay-host.secureserver.net & getting email on gmail and yahoo account but not getting it on my godaddy account
using smtp server address as relay-host.secureserver.net getting email on gmail and yahoo account but not getting it on my godaddy account. Please help me out, ...

How to use net use?
Please can any one tell me how to use the dos command net use properly? I have read the help but can't seem to get it to work. Keep getting sytax error message. Thanks in advance. "Beowulf" <who-knows@no-one.com> wrote in message news:9krutk$puu$1@news.grc.com... > Please can any one tell me how to use the dos command net use properly? > > I have read the help but can't seem to get it to work. Keep getting sytax > error message. what are you trying to do? There are about 50 options to "net use" that do a ton of different thin...

Where to start and how did you get started?
Hi, I have had a feeling for a long time to jump into the adds market for some time due to my low income (shooting for the stars) and I don't have anything better to do these days. But I find it really difficult not to give up due to lack of guides (what I can find atleast) and all the hard words which only makes me confused. But I won't give up. Never. Not sure if this is the right place to post this, but I deffinitly would be really greatfull for help getting started. How did you get started? +If there are any teacher that wanna show me the ropes private, I can give payment with ...

How do I get started with AJAX.Net?
Hi All, I'm a seasoned asp.net developer but have not yet ventured into atlas et al.  I prefer books, but will take whatever I can get if it's good and will get me going. Any recommendations? Thx in advance. Jeff try here first http://ajax.asp.net/downloads/default.aspx?tabid=47 then learn from sample and docJames Wu (MIB426).NET is only way to goMCP, MCSE, MCDBA, MCSD, MCAD I find the materials online display features and implementations but are lacking architectural depth, and am seeking more comprehensive resources. By architectural depth, I mean that I cannot watch ...

Getting started using XML
Hi All,       I am not an expert in XML. Just have few general idea about XML like xsd and xpath and all those stuffs. I have never worked with it but now the situation demands me to and that too very quickly. I have to use an external webservice for my data. I am basically dealing with the live stock market data. I have to code around a bit and then the response from the webservice is as follows.. .......................THIS IS MY REQUEST...........................................................................................................................

Getting started .net website
Hi folks,Does anyone here know of a good website to just sit back and read for learning .net? Thanks in advance.Baldeep Right here... Click the Get Started and Learn sections here. Quite a few out there - - this one, has a lot of good videos -  also ASPNet101.com, but then, I might be a little prejudiced David WierMCP/ASPInsiderASPNet101.com - where to look first!Please Vote for ASPNet101 - 'Best Community Resource'!Control Grouper - easily control properties for multiple controls with one control!Calendar Express - The Best HTML Calendar Generator on the web!(P...

Getting started with JScript.NET
I'm a Javascript and Actionscript developer, and the thought of being able to do server-sides in something I know was too good to resist. Does anyone know some good tutorials for developing ASP.NET pages in JScript?  I can find lots of console code, but simple things are hard: like I can't even figure out how to print something out to the web page (just a string). What I'm really trying to do is access a database, verify a login, and print JSON out to the response.  What should I do to start?  Is there a better way to do this? (IE: using some JSON library already?). I'm commun...

Getting Started with .net and a few questions
Hello I've done some asp and php programming along with various other languages in the past and slowing getting my head around .net.I have a small project of creating a Holiday Booking system on our Intranet and just trying to get the first part to work properly will hopefully get me sorted for the whole project. The Intranet is running on .net 2 and I prefer to use the VB code rather than C#. This is connecting to an SQL server.My initial page that I am trying to create is just for an admin user to view which dates in a table have been specified as Bank Holidays and be able to add ...

Web resources about - Using Exceptions - asp.net.getting-started

Motor vehicle exception - Wikipedia, the free encyclopedia
The exception is based on the idea that there is a lower expectation of privacy in motor vehicles due to the regulations they operate. Additionally, ...

Podcast #42 – It’s The Exception That Proves The Rule
... Language and Usage , which was frustrated by the high number of certain types of questions that were coming in. Is this podcast the exception ...

RWW News: Marco Rubio Reiterates His Opposition To Rape Or Incest Exceptions - YouTube
http://www.rightwingwatch.org/content/marco-rubio-reiterates-his-opposition-rape-or-incest-exceptions Right Wing Watch reports on the extreme ...

Can Tunisia, the 'Arab exception', hold on to democractic ideals amid turmoil?
The terrorist attack on the Bardo Museum, in Tunis, represents yet another episode of senseless, barbaric violence in the name of Islam.

Bike thefts spike in exception to drop in crime
Bicycle thefts in Canberra soar to highest level in nine years, with a 28 per cent jump in three months.

Many rugby films wind up in dead ball area but The Ground We Won is an exception
If rugby is the game they play in heaven, rugby movies generally come from a lesser place.

Most consumers better off after carbon tax scrapped – with one possible exception
Households are roughly $550 a year better off since the scraping of the carbon tax, but air travellers may wonder if they are being overcharged, ...

Men Need to Admit That Jian Ghomeshi Is No Exception
That men like Jian Ghomeshi are a terrible exception and if we as men simply stand up and say we are not as bad as that, or that we are not rapists ...

China, Thailand reach visa exception agreement
China, Thailand reach visa exception agreement People's Daily Online ... this at a forum on China's foreign diplomacy held in Beijing. Both ...

No exception allowed in graft crackdown: People's Daily
No exception allowed in graft crackdown: People's Daily - Ecns.cn ecns The expulsion of Ling Jihua from the Communist Party of China (CPC) ...

Resources last updated: 12/26/2015 2:37:43 AM