473,800 Members | 2,599 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

What's wring with this try-catch block?

This is freaking me out. I'm using Membership and trying to determine if the
database is online. The GetConnectionSt ring( ) method returns a connection
string as expected but not when used in the try block.

I have the Open() and Close() methods commented out while using the
Response.Redire ct to test.
The code in the try block as shown will --never execute-- but the code in
the catch block --always executes-- whether the database is online or not.

WTF???

protected void LoginButton_Cli ck(object sender, EventArgs e)
{
// Redirect proves this test works
//Response.Redire ct(ResolveUrl(" ~/homepage.aspx?L oginButton_Clic k"));

SqlConnection testConnection = new
SqlConnection(G etConnectionStr ing("MyConnecti onString"));
if (!String.IsNull OrEmpty(testCon nection.ToStrin g()))
{
try
{
//testConnection. Open();
//testConnection. Close();
Response.Redire ct(ResolveUrl(" ~/homepage.aspx?M yConnectionStri ng-Found"));
}
catch (Exception ex)
{
Response.Redire ct(ResolveUrl(" ~/homepage.aspx?L oginButton_Clic k-Caught-Exception"));
}
}
}

Aug 1 '08
16 2174

"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:MP******** *************@m snews.microsoft .com...
HillBilly <so******@somew here.comwrote:
Response.Redire ct works by setting something and then throwing an
exception (by default). If you look at the exception which is being
thrown, I susect you'll find it's a ThreadAbortExce ption. Look at the
documentation for Response.Redire ct for more information.

Aha! I'll certainly study that thank you but still, what do you do to
determine if the database is offline? I thought I'd convert the code into
a
method called before logging in or any other attempt to access the
database.
But if its not even online then what?

Trying to connect (and executing some basic operation) seems reasonable
to me - but unconnected to the problem you're seeing. I suggest you
extract the desired functionality (basically an "online/offline"
boolean check) into a separate method - that way you'll be catching
just the database exception there, rather than both the database
exception *and* the exception from the redirect.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
I refactored as this implementation. ..

#region Method: IsDatabaseOffli ne()...
public void IsDatabaseOffli ne()
{
SqlConnection connection = new
SqlConnection(G etConnectionStr ing("MyConnecti onString"));
if (!String.IsNull OrEmpty(connect ion.ToString()) )
{
try
{
connection.Open ();
connection.Clos e();
connection.Disp ose();
}
catch (SqlException ex)
{
Response.Redire ct(ResolveUrl(" ~/ErrorPages/DatabaseError.a spx?Caught-SqlException")) ;
}
}
}
#endregion

You know I didn't even need the redirect in the try block but it sure taught
me a lesson in two ways. First, I've learned about ThreadAbortExce ption and
secondly I realized when the IsDatabaseOffli ne method is marked static it
causes an error because the SqlConnection object is not static which implies
all members of a static method must themselves be static.

More work to write the log and notification code but this should be muy
bueno for now eh?

Aug 2 '08 #11
HillBilly <so******@somew here.comwrote:
I refactored as this implementation. ..

#region Method: IsDatabaseOffli ne()...
public void IsDatabaseOffli ne()
{
SqlConnection connection = new
SqlConnection(G etConnectionStr ing("MyConnecti onString"));
if (!String.IsNull OrEmpty(connect ion.ToString()) )
{
try
{
connection.Open ();
connection.Clos e();
connection.Disp ose();
}
catch (SqlException ex)
{
Response.Redire ct(ResolveUrl(" ~/ErrorPages/DatabaseError.a spx?Caught-SqlException")) ;
}
}
}
#endregion
No, that is still a bad thing in my view, for a few reasons:

1) You're mixing your database logic with your page logic. What if you
ever want to create a page with diagnostics of various things? Or use
this code for something other than a web page?

2) A method called "IsDatabaseOffl ine" really should return something.
Based on the method name I *certainly* wouldn't expect it to be
redirecting a response.

3) You should still use a "using" statement for the connection, IMO.
That way you don't need to explicitly close it or call Dispose (doing
both is reasonably pointless, btw) but you'll still close it if
something odd (like an asynchronous exception) happens after Open.

4) It may well be worth actually *doing* something with the connection
- something which forces it to try to talk to the database for real.
Otherwise you may find you've got stale connections which can be opened
and closed with no problems, but can't do any real work. I know that's
a problem with some connections on some platforms, but I don't know if
it's relevant in your particular situation.
You know I didn't even need the redirect in the try block but it sure taught
me a lesson in two ways. First, I've learned about ThreadAbortExce ption and
secondly I realized when the IsDatabaseOffli ne method is marked static it
causes an error because the SqlConnection object is not static which implies
all members of a static method must themselves be static.
The SqlConnection object is declared inside the method - it's
irrelevent. However, the Response property isn't static, and
GetConnectionSt ring may not be depending on what you're doing.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Aug 2 '08 #12

"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:MP******** *************@m snews.microsoft .com...
HillBilly <so******@somew here.comwrote:
>I refactored as this implementation. ..

#region Method: IsDatabaseOffli ne()...
public void IsDatabaseOffli ne()
{
SqlConnection connection = new
SqlConnection( GetConnectionSt ring("MyConnect ionString"));
if (!String.IsNull OrEmpty(connect ion.ToString()) )
{
try
{
connection.Open ();
connection.Clos e();
connection.Disp ose();
}
catch (SqlException ex)
{

Response.Redir ect(ResolveUrl( "~/ErrorPages/DatabaseError.a spx?Caught-SqlException")) ;
}
}
}
#endregion

No, that is still a bad thing in my view, for a few reasons:

1) You're mixing your database logic with your page logic. What if you
ever want to create a page with diagnostics of various things? Or use
this code for something other than a web page?

2) A method called "IsDatabaseOffl ine" really should return something.
Based on the method name I *certainly* wouldn't expect it to be
redirecting a response.

3) You should still use a "using" statement for the connection, IMO.
That way you don't need to explicitly close it or call Dispose (doing
both is reasonably pointless, btw) but you'll still close it if
something odd (like an asynchronous exception) happens after Open.

4) It may well be worth actually *doing* something with the connection
- something which forces it to try to talk to the database for real.
Otherwise you may find you've got stale connections which can be opened
and closed with no problems, but can't do any real work. I know that's
a problem with some connections on some platforms, but I don't know if
it's relevant in your particular situation.
>You know I didn't even need the redirect in the try block but it sure
taught
me a lesson in two ways. First, I've learned about ThreadAbortExce ption
and
secondly I realized when the IsDatabaseOffli ne method is marked static it
causes an error because the SqlConnection object is not static which
implies
all members of a static method must themselves be static.

The SqlConnection object is declared inside the method - it's
irrelevent. However, the Response property isn't static, and
GetConnectionSt ring may not be depending on what you're doing.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
So when all is said and done I should not try to write superfluous code
worrying about the database being offline as that circumstance should and
would be caught with a SqlException anyway? And how is the exception cuaght
when using the 2.0 Login controls without rewriting authentication?
Aug 3 '08 #13
HillBilly <so******@somew here.comwrote:

<snip>
So when all is said and done I should not try to write superfluous code
worrying about the database being offline as that circumstance should and
would be caught with a SqlException anyway?
Well, that's one option. But my point was mostly to separate out the
test for whether or not the database is online from what you happen to
want to do at the moment when the database is offline.

Write a simple method which tests for database connectivity and returns
the status (for the moment a simple bool would do) - and then act on
that return value. That's a much more flexible approach.
And how is the exception cuaght
when using the 2.0 Login controls without rewriting authentication?
No idea, I'm afraid. I'd ask on an ASP.NET group. Be aware that the
database could go offline after you do your check though, of course.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Aug 3 '08 #14

"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:MP******** *************@m snews.microsoft .com...
HillBilly <so******@somew here.comwrote:

<snip>
>So when all is said and done I should not try to write superfluous code
worrying about the database being offline as that circumstance should and
would be caught with a SqlException anyway?

Well, that's one option. But my point was mostly to separate out the
test for whether or not the database is online from what you happen to
want to do at the moment when the database is offline.

Write a simple method which tests for database connectivity and returns
the status (for the moment a simple bool would do) - and then act on
that return value. That's a much more flexible approach.
>And how is the exception cuaght
when using the 2.0 Login controls without rewriting authentication?

No idea, I'm afraid. I'd ask on an ASP.NET group. Be aware that the
database could go offline after you do your check though, of course.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Offline --after-- logging in? Gees that's a stunning thought ;-) so please,
one more comment if you would as I appreciate your attention. I thought --I
was writing a simple method-- which tests for database connectivity? I'm
asking myself how much simpler could it get than to start with the
connection which either is or isn't active and hence would fail and easily
be caught. The impetus to put it into a method I was thinking makes it
possible for reuse everywhere there is an initial request to access and use
the database as you said it yourself, "what happens when the database goes
offline afterwards?" And that can't be prevented by the web developer nor
caught in any way I can imagine.

Its not like I haven't studied the context of this issue looking all over
the place and there doesn't seem to be much of anything anywhere other than
our colleagues blogging or documenting SqlExceptions in general.

I'm going the route of writing more code. I mean what the hell. I'll only
learn yet more along the way. But you know what they say eh? All developers
are lazy so I just wanted to be like everybody else. :-)

Aug 3 '08 #15
HillBilly <so******@somew here.comwrote:
Offline --after-- logging in?
That's one possibility. Another is that it goes offline *after* you've
tested connectivity, but *before* you've actually done the login.
Basically I'm saying that any test you do is stale immediately after
you've done it. That's not to say it's not worth doing, but just bear
the possibility in mind :)
so please, one more comment if you would as I appreciate your
attention. I thought --I was writing a simple method-- which tests
for database connectivity? I'm asking myself how much simpler could
it get than to start with the connection which either is or isn't
active and hence would fail and easily be caught.
Sounds reasonable to me.
The impetus to put it into a method I was thinking makes it possible
for reuse everywhere there is an initial request to access and use
the database as you said it yourself, "what happens when the database
goes offline afterwards?" And that can't be prevented by the web
developer nor caught in any way I can imagine.
Indeed. There's really not a lot you can do about it, other than be
aware of the remote possibility, and deal with it *reasonably*
gracefully (in particular, don't try to log the error to the
database!).

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Aug 3 '08 #16
<snip />
Thanks for hanging out Jon. Onward...
Aug 4 '08 #17

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

Similar topics

125
14865
by: Sarah Tanembaum | last post by:
Beside its an opensource and supported by community, what's the fundamental differences between PostgreSQL and those high-price commercial database (and some are bloated such as Oracle) from software giant such as Microsoft SQL Server, Oracle, and Sybase? Is PostgreSQL reliable enough to be used for high-end commercial application? Thanks
11
2510
by: Sims | last post by:
Hi, I have a function that looks something like .... void Function( std::string &oldval ) { int iSome_size = xxx; // get some size char *tmp = NULL; tmp = new char;
72
5904
by: E. Robert Tisdale | last post by:
What makes a good C/C++ programmer? Would you be surprised if I told you that it has almost nothing to do with your knowledge of C or C++? There isn't much difference in productivity, for example, between a C/C++ programmers with a few weeks of experience and a C/C++ programmer with years of experience. You don't really need to understand the subtle details or use the obscure features of either language
22
3770
by: MLH | last post by:
I have some audio help files that play fine from within Access 97 and Access 2.0. Both are running on a Windows XP box. But I do not know what program plays the files. If I click Start, Run and type in c:\MyApp\MyHelp\Help1.wav, Windows Media Player tries unsuccessfully to play the wav file. It err's saying ClassFactory cannot supply the requested class. But WMP has no problem at all playing c:\windows\system32\ ALSNDMGR.WAV. That goes...
5
7388
by: Peter | last post by:
Team VB.net, I have multiple programs that need a tool to count lines in a text files. I have been solving this problem through writing proceedures but I hate cutting and pasting code. Is there an easy way of making a "module" or object that I would be able to pass a string variable "c:\MyTextFile" to and then have it run this proceedure on it?
34
2817
by: Ross Reyes | last post by:
HI - Sorry for maybe a too simple a question but I googled and also checked my reference O'Reilly Learning Python book and I did not find a satisfactory answer. When I use readlines, what happens if the number of lines is huge? I have a very big file (4GB) I want to read in, but I'm sure there must be some limitation to readlines and I'd like to know how it is handled by python. I am using it like this:
16
3754
by: Matthew Zhou | last post by:
I am a students learning programming, and want to do some software projects to practice myself. However, no one will only use one language to make all the tasks done. And every languages has its strong and relatively weak side. So, what about C? Many friends of mine suggest me move to C++ or Java. But I there must be some places reserved for C (although they say C++ can do all the jobs of C).
1
2407
by: td0g03 | last post by:
Hello, I am new to C and I am new to English. I not sure what palindromes mean. I don't know exactly what my teacher wants me to do. If someone could explain it to me in a different way that would be great. I know its sorta long, but maybe you only have to few the first few paragraphs. Problem: Write a program in C that generates number palindromes using the algorithm below (see 3. on the next page) and allows the user to try this...
1
1718
by: Sean128 | last post by:
Hi, I hope someone can help me - this seems like it should be a really simple problem but I've been having trouble trying to solve it all week. I have hosted my website on a Linux server in 1 and 1 that I can not modefiy the Apache server. They told me I need to create the .htaccess file. The code that I put in my Biocon folder in my .htaccess file is: php_value include_path "/bioconstore/lib:/plate-latest"
5
1742
by: Max Ivanov | last post by:
Hi all! When and where I should use try-except-finally statement? What is the difference between: -------- try: A... except: B.... finally: C...
0
9690
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9551
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
10274
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
10251
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
9085
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7576
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
5469
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5606
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4149
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

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.