473,396 Members | 1,907 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,396 software developers and data experts.

Try Catch and Variables

Hi

I am trying to do something really simple. Create a method within a
class which will connect to the database, pull back a result and
return it out the method. Not hard.

All my database connections and executescalar work fine, but, I want
to put it into a Try Catch statement so that if a problem occurs, it
will error out to my error page.

How can I do all this and return a value within the Try Catch???

public int getUserIdByUsernamePassword(String username, String
userPassword)
{
try
{
databaseConnect.Open();

int userId;

cmdGetUserDetailsByUsernamePassword.Parameters["@username"].Value =
username;
cmdGetUserDetailsByUsernamePassword.Parameters["@userPassword"].Value
= userPassword;

userId = (int)cmdGetUserDetailsByUsernamePassword.ExecuteSc alar();

return userId

}
catch
{
// Error page call.
}

}

The method does not recognise the fact that I have a returned a value.

Hopefully someone can give me an explanation how I can still have the
benefits of a Try Catch statement while still being able to return a
value out of the method.

Thank you very much
Nov 16 '05 #1
10 5685
Bungle wrote:

public int getUserIdByUsernamePassword(String username, String
userPassword)
{ int userId -1; try
{
databaseConnect.Open();

cmdGetUserDetailsByUsernamePassword.Parameters["@username"].Value =
username;
cmdGetUserDetailsByUsernamePassword.Parameters["@userPassword"].Value
= userPassword;

userId = (int)cmdGetUserDetailsByUsernamePassword.ExecuteSc alar();

} catch(Exception ex) {
// Error page call.
} finally
{
return userId
}
}


This for example should solve all your problems, if I get your problem
right.

The finally statement is executed every time after the catch was
processed, or the try worked perfectly.

I use this for Database rollback or commit stuff. A very usefull construct!

Best Regards,

Martin
Nov 16 '05 #2
Hi,

Put a return statement into catch block or at the end of method.
You'll make compiler happy.

--
Miha Markic [MVP C#] - RightHand .NET consulting & software development
miha at rthand com
www.rthand.com

"Bungle" <bu****@wizardbuy.com> wrote in message
news:de**************************@posting.google.c om...
Hi

I am trying to do something really simple. Create a method within a
class which will connect to the database, pull back a result and
return it out the method. Not hard.

All my database connections and executescalar work fine, but, I want
to put it into a Try Catch statement so that if a problem occurs, it
will error out to my error page.

How can I do all this and return a value within the Try Catch???

public int getUserIdByUsernamePassword(String username, String
userPassword)
{
try
{
databaseConnect.Open();

int userId;

cmdGetUserDetailsByUsernamePassword.Parameters["@username"].Value =
username;
cmdGetUserDetailsByUsernamePassword.Parameters["@userPassword"].Value
= userPassword;

userId = (int)cmdGetUserDetailsByUsernamePassword.ExecuteSc alar();

return userId

}
catch
{
// Error page call.
}

}

The method does not recognise the fact that I have a returned a value.

Hopefully someone can give me an explanation how I can still have the
benefits of a Try Catch statement while still being able to return a
value out of the method.

Thank you very much

Nov 16 '05 #3
Thanks for the reply Martin.

Unfortunately it does not like the return in the finally statement.

It gives the error "Control cannot leave the body of a finally clause"??

These were the kind of walls I kept hitting.

Thanks

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #4
Hi,

There is no need for a return statement in finally block as if (unhandled)
exception happens there is no return value anyway.

--
Miha Markic [MVP C#] - DXSquad/RightHand .NET consulting & software
development
miha at rthand com www.rthand.com

Developer Express newsgroups are for peer-to-peer support.
For direct support from Developer Express, write to su*****@devexpress.com
Bug reports should be directed to: su*****@devexpress.com
Due to newsgroup guidelines, DX-Squad will not answer anonymous postings.

"mphanke" <mp*****@nospam.nospam> wrote in message
news:%2***************@TK2MSFTNGP11.phx.gbl...
Bungle wrote:

public int getUserIdByUsernamePassword(String username, String
userPassword)
{ int userId -1;
try
{
databaseConnect.Open();

cmdGetUserDetailsByUsernamePassword.Parameters["@username"].Value =
username;
cmdGetUserDetailsByUsernamePassword.Parameters["@userPassword"].Value
= userPassword;

userId = (int)cmdGetUserDetailsByUsernamePassword.ExecuteSc alar();

}

catch(Exception ex)
{
// Error page call.
}

finally
{
return userId
}

}


This for example should solve all your problems, if I get your problem
right.

The finally statement is executed every time after the catch was
processed, or the try worked perfectly.

I use this for Database rollback or commit stuff. A very usefull

construct!
Best Regards,

Martin

Nov 16 '05 #5
You need to either return a value (say -1) in you catch block, move
the return to after the catch block, or rethrow the exception in you
catch block.

All paths through the function must either return an appropriate value
or throw an exception.

Adam
Nov 16 '05 #6
<"Miha Markic [MVP C#]" <miha at rthand com>> wrote:
There is no need for a return statement in finally block as if (unhandled)
exception happens there is no return value anyway.


Well, that depends on what the language specifies. Java specifies that
if a finally clause completes abruptly (eg a return or an exception)
then the result of the whole method is that abrupt completion - in
other words, a return in a finally clause can sort of "override" any
exception (or other return value).

C# just doesn't allow return from finally at all, so no semantics need
to be defined for that bit.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #7
Hi Jon,

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP***********************@msnews.microsoft.co m...
<"Miha Markic [MVP C#]" <miha at rthand com>> wrote:
There is no need for a return statement in finally block as if (unhandled) exception happens there is no return value anyway.


Well, that depends on what the language specifies. Java specifies that
if a finally clause completes abruptly (eg a return or an exception)
then the result of the whole method is that abrupt completion - in
other words, a return in a finally clause can sort of "override" any
exception (or other return value).

C# just doesn't allow return from finally at all, so no semantics need
to be defined for that bit.


I was kinda talking about C# :-)

--
Miha Markic [MVP C#] - RightHand .NET consulting & software development
miha at rthand com
www.rthand.com
Nov 16 '05 #8
Miha Markic [MVP C#] wrote:
Hi,

There is no need for a return statement in finally block as if (unhandled)
exception happens there is no return value anyway.

Okay,

I mixed up stuff - didn't have the source with me...
This is one of the things I just can't keep in mind!

Martin
Nov 16 '05 #9
<"Miha Markic [MVP C#]" <miha at rthand com>> wrote:
C# just doesn't allow return from finally at all, so no semantics need
to be defined for that bit.


I was kinda talking about C# :-)


Sure, so was I. Your statement about "there's no need for a return
value" assumes that if you *could* return from a finally block, the
return value would be ignored. I was pointing out that this assumption
is invalid as the language designers could choose to do whatever they
want - just as the Java designers chose that the return value would
take precedence over the exception.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10
Let's address this one step at a time.

The first problem is that compile is say that no all paths return a
value, because, it's assuming that the catch is dealing with the problem and
the function is continuing on after the catch.

Solution: Move the return outside the try/catch.
public int getUserIdByUsernamePassword(String username, String userPassword)
{
try
{
// :
}
catch
{
// :
}
return userId
}

New Problem: Undefined variable error, as userId is now out of scope.
(it lived & died inside the try{})

Solution: Move the definition of userId outside of the try/catch.

public int getUserIdByUsernamePassword(String username, String userPassword)
{
int userId;

try
{
// :
}
catch
{
// :
}
return userId
}

Newer problem: The compiler should now complain about the possibility of
return an uninitialized variable.

Solution: Initialize userId to an error value when it is defined:

public int getUserIdByUsernamePassword(String username, String userPassword)
{
int userId = 0;

try
{
// :
}
catch
{
// :
}
return userId
}
--
Truth,
James Curran
Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com
(note new day job!)
"Bungle" <bu****@wizardbuy.com> wrote in message
news:de**************************@posting.google.c om...
Hi

I am trying to do something really simple. Create a method within a
class which will connect to the database, pull back a result and
return it out the method. Not hard.

All my database connections and executescalar work fine, but, I want
to put it into a Try Catch statement so that if a problem occurs, it
will error out to my error page.

How can I do all this and return a value within the Try Catch???

public int getUserIdByUsernamePassword(String username, String
userPassword)
{
try
{
databaseConnect.Open();

int userId;

cmdGetUserDetailsByUsernamePassword.Parameters["@username"].Value =
username;
cmdGetUserDetailsByUsernamePassword.Parameters["@userPassword"].Value
= userPassword;

userId = (int)cmdGetUserDetailsByUsernamePassword.ExecuteSc alar();

return userId

}
catch
{
// Error page call.
}

}

The method does not recognise the fact that I have a returned a value.

Hopefully someone can give me an explanation how I can still have the
benefits of a Try Catch statement while still being able to return a
value out of the method.

Thank you very much

Nov 16 '05 #11

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

Similar topics

5
by: Mike P | last post by:
I'm trying to split up a large procedure into several try catch blocks in order to catch different errors. However, when I split my code up like this, my variables that I am using throughout the...
6
by: ChrisB | last post by:
Hello All: I notice that when using try/catch blocks in C#, variables declared in the try block go out of scope in the finally block. So, for example, the following code generates a compiler...
23
by: VB Programmer | last post by:
Variable scope doesn't make sense to me when it comes to Try Catch Finally. Example: In order to close/dispose a db connection you have to dim the connection outside of the Try Catch Finally...
1
by: Tan Hong Giap | last post by:
HI, Does any one has a better ideal of handling error with try..catch for the following scenario. 1. the process could cause many kinds of error. which means the nested try..catch may happen....
7
by: What-A-Tool | last post by:
In the following code, "catch" is underlined in blue, and the error "the variable fx is declared but never used" is displayed when I mouse hover over it. Am I doing something wrong, or do I just...
23
by: pigeonrandle | last post by:
Hi, Does this bit of code represent complete overkill?! try { //create a treenode TreeNode tn = new TreeNode(); //add it to a treeview tv.Nodes.Add(tn);
28
by: RickHodder | last post by:
I'm getting frustrated with using try...catch with local variables: The code below wont compile in .NET 1.1: I get the following error: "Use of unassigned local variable 'oProcessFileReader' " ...
12
by: reycri | last post by:
While the following is allowed: if (a == b) SomeFunction(); else OtherFunction(); The following is not: try
14
by: Jake K | last post by:
How do I access variables that are set within a try/catch block? The following code produces a use of unassigned local variable error: string varOne; try { //access database here, select,...
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:
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...

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.