473,790 Members | 2,380 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

return null upon exception?

Suppose I have a method that returns some type of object, and in that method
I have a try...catch block and just throw my own exception when I catch one.
The compiler insists that all code paths return a value, so...

do I just put
return null;
after I throw my exception in the catch block?

or should I initialize the local variable to null and return it in a finally
block?

or something else entirely, or is it just personal taste?

Thanks.
Nov 15 '05 #1
8 1859
"Daniel Billingsley" <db**********@N O.durcon.SPAAMM .com> wrote in
news:u3******** ******@tk2msftn gp13.phx.gbl:
Suppose I have a method that returns some type of object, and in that
method I have a try...catch block and just throw my own exception when
I catch one. The compiler insists that all code paths return a value,
so...

do I just put
return null;
after I throw my exception in the catch block?

or should I initialize the local variable to null and return it in a
finally block?

or something else entirely, or is it just personal taste?


As you say, its pretty much personal taste...

No matter how you do it, the most important thing is to document the
function so that the user (perhaps just yourself) knows that null is a
valid return value (indicating failure), and you should TEST the return
value in the calling code to see if it is null before using it.

-mbray
Nov 15 '05 #2
This doesn't seem to be a correct diagnosis of the error, since (in my
experience) a "throw" suffices as a "return" for a given code path. For
instance, this should compile (and run, and throw) with no problem:

public string ThrowsBeforeRet urn() {
int x = 1;
if (x == 1) throw new Exception("Oops !");
else return "no throw";
}

-Marc
"Daniel Billingsley" <db**********@N O.durcon.SPAAMM .com> wrote in message
news:u3******** ******@tk2msftn gp13.phx.gbl...
Suppose I have a method that returns some type of object, and in that method I have a try...catch block and just throw my own exception when I catch one. The compiler insists that all code paths return a value, so...

do I just put
return null;
after I throw my exception in the catch block?

or should I initialize the local variable to null and return it in a finally block?

or something else entirely, or is it just personal taste?

Thanks.

Nov 15 '05 #3
Daniel Billingsley wrote:
Suppose I have a method that returns some type of object, and in that method
I have a try...catch block and just throw my own exception when I catch one.
The compiler insists that all code paths return a value, so...

do I just put
return null;
after I throw my exception in the catch block?

or should I initialize the local variable to null and return it in a finally
block?

or something else entirely, or is it just personal taste?

Thanks.


A code path that throws an exception does not need to return anything
(in fact, it can't). You should post a sample of what you're doing and
the error you get.

--
mikeb

Nov 15 '05 #4
"Marc Lewandowski" <ma**@telebill. com> wrote in
news:OJ******** ******@tk2msftn gp13.phx.gbl:
This doesn't seem to be a correct diagnosis of the error, since (in my
experience) a "throw" suffices as a "return" for a given code path.
For instance, this should compile (and run, and throw) with no
problem:

public string ThrowsBeforeRet urn() {
int x = 1;
if (x == 1) throw new Exception("Oops !");
else return "no throw";
}

-Marc


You are right - I didn't quite understand the original question (or I
didn't read it correctly)... It seems, however, after reading the
original question, that there WAS a code path that wasn't returning a
value, which would indicate a possible logic error, or just
inexperienced programming. I'm guessing that they wrote code something
like:

public string NoReturnValue()
{
int x = 1;
if (x > 0) return x;
throw new Exception("Oops ");
}

and never "returning a value" at the end of the function.

As far as code REQUIRING a return value, you are correct - there's
nothing wrong with the code you've presented. However, I prefer to
reserve throwing exceptions for unusual circumstances where the error is
significant enough that the code can't continue. This is different from
returning an error, which is a "possible expected outcome".

-mbray
Nov 15 '05 #5

the errors don't actually have anything to do with each other. If you
rethrow your exception in the catch it makes no difference to anything
you are returning since when the exception comes out its not going to
return a value anyway.

you shouldn't have any 'return' or anything after your throw statement
in your catch block. However, unless the throw is unavoidable in code
then you need to return something at the end of your routine.
Allen Anderson
http://www.glacialcomponents.com
mailto: allen@put my website url here.com
On Wed, 15 Oct 2003 11:24:51 -0400, "Daniel Billingsley"
<db**********@N O.durcon.SPAAMM .com> wrote:
Suppose I have a method that returns some type of object, and in that method
I have a try...catch block and just throw my own exception when I catch one.
The compiler insists that all code paths return a value, so...

do I just put
return null;
after I throw my exception in the catch block?

or should I initialize the local variable to null and return it in a finally
block?

or something else entirely, or is it just personal taste?

Thanks.


Nov 15 '05 #6
Ah, yes you're right.

(I'm trying to work through some sample code and understand what it's doing
as I learn C# and Ado.NET)

It calls a private method in the catch block to actually throw the exception
so that a trace write can be performed in that method as well - good idea
for code reuse but not so good for this compiler constraint. I suppose the
better way to do that would be to put the Trace calls in the custom
exception's constructor overrides, eh?

"Marc Lewandowski" <ma**@telebill. com> wrote in message
news:OJ******** ******@tk2msftn gp13.phx.gbl...
This doesn't seem to be a correct diagnosis of the error, since (in my
experience) a "throw" suffices as a "return" for a given code path. For
instance, this should compile (and run, and throw) with no problem:

public string ThrowsBeforeRet urn() {
int x = 1;
if (x == 1) throw new Exception("Oops !");
else return "no throw";
}

-Marc
"Daniel Billingsley" <db**********@N O.durcon.SPAAMM .com> wrote in message
news:u3******** ******@tk2msftn gp13.phx.gbl...
Suppose I have a method that returns some type of object, and in that

method
I have a try...catch block and just throw my own exception when I catch

one.
The compiler insists that all code paths return a value, so...

do I just put
return null;
after I throw my exception in the catch block?

or should I initialize the local variable to null and return it in a

finally
block?

or something else entirely, or is it just personal taste?

Thanks.


Nov 15 '05 #7
Daniel Billingsley wrote:
Ah, yes you're right.

(I'm trying to work through some sample code and understand what it's doing
as I learn C# and Ado.NET)

It calls a private method in the catch block to actually throw the exception
so that a trace write can be performed in that method as well - good idea
for code reuse but not so good for this compiler constraint. I suppose the
better way to do that would be to put the Trace calls in the custom
exception's constructor overrides, eh?

That would be one way - possibly the best. However, if you do need to
call another method in your catch block you can cleanly work around this
problem by having that method return the exception to be thrown instead
of having it throw the exception itself:

try {
// ...
}
catch {
throw( MyPrivateExcept ionLogger());
}
"Marc Lewandowski" <ma**@telebill. com> wrote in message
news:OJ******** ******@tk2msftn gp13.phx.gbl...
This doesn't seem to be a correct diagnosis of the error, since (in my
experience) a "throw" suffices as a "return" for a given code path. For
instance, this should compile (and run, and throw) with no problem:

public string ThrowsBeforeRet urn() {
int x = 1;
if (x == 1) throw new Exception("Oops !");
else return "no throw";
}

-Marc
"Daniel Billingsley" <db**********@N O.durcon.SPAAMM .com> wrote in message
news:u3****** ********@tk2msf tngp13.phx.gbl. ..
Suppose I have a method that returns some type of object, and in that


method
I have a try...catch block and just throw my own exception when I catch


one.
The compiler insists that all code paths return a value, so...

do I just put
return null;
after I throw my exception in the catch block?

or should I initialize the local variable to null and return it in a


finally
block?

or something else entirely, or is it just personal taste?

Thanks.




--
mikeb

Nov 15 '05 #8
Instead of:

void ThrowMyExceptio n() { throw new Exception("my message"); }

int MyMethod() {
if (ok) return 1;
else {
ThrowMyExceptio n();
return 0; // compiler needs a return or throw here because it does
not know this will never be reached
}
}

I would suggest:

Exception MyException() { return new Exception("my message"); }

int MyMethod() {
if (ok) return 1;
else throw MyException(); // compiler is happy now
}

I don't know if this is really your problem, but it sounds like it.

Bruno.

"Daniel Billingsley" <db**********@N O.durcon.SPAAMM .com> a écrit dans le
message de news:O1******** ********@TK2MSF TNGP12.phx.gbl. ..
Ah, yes you're right.

(I'm trying to work through some sample code and understand what it's doing as I learn C# and Ado.NET)

It calls a private method in the catch block to actually throw the exception so that a trace write can be performed in that method as well - good idea
for code reuse but not so good for this compiler constraint. I suppose the better way to do that would be to put the Trace calls in the custom
exception's constructor overrides, eh?

"Marc Lewandowski" <ma**@telebill. com> wrote in message
news:OJ******** ******@tk2msftn gp13.phx.gbl...
This doesn't seem to be a correct diagnosis of the error, since (in my
experience) a "throw" suffices as a "return" for a given code path. For
instance, this should compile (and run, and throw) with no problem:

public string ThrowsBeforeRet urn() {
int x = 1;
if (x == 1) throw new Exception("Oops !");
else return "no throw";
}

-Marc
"Daniel Billingsley" <db**********@N O.durcon.SPAAMM .com> wrote in message news:u3******** ******@tk2msftn gp13.phx.gbl...
Suppose I have a method that returns some type of object, and in that

method
I have a try...catch block and just throw my own exception when I
catch one.
The compiler insists that all code paths return a value, so...

do I just put
return null;
after I throw my exception in the catch block?

or should I initialize the local variable to null and return it in a

finally
block?

or something else entirely, or is it just personal taste?

Thanks.



Nov 15 '05 #9

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

Similar topics

1
4346
by: jennifer johnson | last post by:
Hello All, I appreciate anyone's assistance. I wanted to validate user customizable field values so I changed my JSP page so that the form action would post existing form - action=<%= getRequestURI() %>. Upon form loading after submit verify field values and if any are left empty a message would be posted, and again form would be reposted until all field values were confirmed not to be empty. If field values were not left blank then it...
94
13912
by: John Bailo | last post by:
The c# *return* statement has been bothering me the past few months. I don't like the fact that you can have different code paths in a method and have multiple return statements. To me, it would be more orthogonal if a method could only have one return statement. --
3
5877
by: Eric the half a Bee | last post by:
Hello I am trying to implement a search function within a collection of Employees. I am searching for a specific EmpID number in the collection, and if it is found, I want to return the Employee. This I can do. The problem comes if the EmpID is not found in the collection. The only way to achieve this I can think of is to throw an invalid argument exception:
2
3998
by: Stuart | last post by:
Hi there I have a stored procedure on my SQL database that retrieves a wide range of values from about 5 different tables. My end point is to calculate the cost against each line of retrieved data. Depending upon the contents of a particular field that cost calculation changes.... I retrieve the data in to a dataset and subsequently in to a datatable - fine so far...
20
7013
by: weston | last post by:
I've got a piece of code where, for all the world, it looks like this fails in IE 6: hometab = document.getElementById('hometab'); but this succeeds: hometabemt = document.getElementById('hometab'); Has anyone ever seen anything like this before, or am I dreaming?
22
4044
by: semedao | last post by:
Hi , I am using asyc sockets p2p connection between 2 clients. when I debug step by step the both sides , i'ts work ok. when I run it , in somepoint (same location in the code) when I want to receive 5 bytes buffer , I call the BeginReceive and then wait on AsyncWaitHandle.WaitOne() but it is signald imidiatly , and the next call to EndReceive return zero bytes length , also the buffer is empty. here is the code: public static byte...
0
1794
by: flyingchen | last post by:
using System; using System.Windows.Forms; using System.Threading; using System.ComponentModel; namespace ProgressControl.Core { public delegate object Execute(params object args); public class ProgressController
2
3105
by: crabsdf | last post by:
My project is a single method class which takes a xml object and, using Apache FOP, transforms it into a PDF which is returned as an output stream. Here is full code package transactionStatement; import javax.xml.transform.TransformerFactory; import javax.servlet.*; import org.jdom.*; import java.io.ByteArrayOutputStream; import java.io.File;
12
1481
by: Matt B | last post by:
I was just wondering if there is a "best" choice from the following couple of ways of returning a value from a method: 1) private HashAlgorithm GetSpecificHashAlgorithm(string hashString){ if (hashString == "MD5") { return System.Security.Cryptography.MD5.Create(); } else { return System.Security.Cryptography.SHA512.Create(); }
0
9512
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
10413
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10145
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
9986
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...
0
9021
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
7530
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
6769
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
5422
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
5551
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.