Returning result in nested try catch block - c#

I am implementing some performance counters and I would like to know your opinion.
The question is should I declare response and return it outside try block or Is it OK to return it directly in the try block. Is there a difference and If so, what sample code is valid (if any).
With best regards, no9.
public string TestMethod(string document)
{
try
{
WebService ws = new WebService();
string response = null;
var startTime = PerformanceCounter.GetPerformanceCounterStartTimeHandle();
try
{
response = ws.InsertDocument(document);
}
catch (Exception ex)
{
PerformanceCounterHelper.Increment(PerformanceCounterEnum.NumberOfExternalWsCallsExceptionOnSec);
throw;
}
finally
{
PerformanceCounterHelper.IncrementPerformanceCounterByElapsedTime(PerformanceCounterEnum.DurationOfExternalCallsInSec, startTime);
PerformanceCounterHelper.Increment(PerformanceCounterEnum.NumberOfExternalCallsOnSec);
}
return response;
}
catch (Exception ex)
{
log.EventError(ex);
throw new DocumentGeneralException();
}
}
versus:
public string TestMethod(string document)
{
try
{
WebService ws = new WebService();
var startTime = PerformanceCounter.GetPerformanceCounterStartTimeHandle();
try
{
return ws.InsertDocument(document);
}
catch (Exception ex)
{
PerformanceCounterHelper.Increment(PerformanceCounterEnum.NumberOfExternalWsCallsExceptionOnSec);
throw;
}
finally
{
PerformanceCounterHelper.IncrementPerformanceCounterByElapsedTime(PerformanceCounterEnum.DurationOfExternalCallsInSec, startTime);
PerformanceCounterHelper.Increment(PerformanceCounterEnum.NumberOfExternalCallsOnSec);
}
}
catch (Exception ex)
{
log.EventError(ex);
throw new DocumentGeneralException();
}
}

As long as there isn't a difference because of not exiting (i.e. it runs additional/different code), then the code is identical. Actually, at the IL level it is illegal to ret from inside a try/catch, so one of the things the compiler does is to do exactly what you have done: introduce a local, assign the local inside the try/catch, then return that value when outside the try/catch.
Basically, go with whatever is simplest and most convenient to read. In your case, I would say "the first one".

Related

Try Catch Exceptions Error

When I use try catch exception with this piece of code, I get the following error:
"not all code paths return values"
My code:
public System.Drawing.Image Scan()
{
try
{
const string formatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
WIA.CommonDialog scanDialog = new WIA.CommonDialog();
WIA.ImageFile imageFile = null;
imageFile = scanDialog.ShowAcquireImage(WIA.WiaDeviceType.ScannerDeviceType, WIA.WiaImageIntent.GrayscaleIntent,
WIA.WiaImageBias.MinimizeSize, formatJPEG, false, true, false);
WIA.Vector vector = imageFile.FileData;
System.Drawing.Image i = System.Drawing.Image.FromStream(new System.IO.MemoryStream((byte[])vector.get_BinaryData()));
return i;
}
catch (COMException ce)
{
if ((uint)ce.ErrorCode == 0x800A03EC)
{
return ce;
}
}
Change your catch block like below will work but still you face some issue. Because your method returns type Image and you are returning COMException in catch block. I suggest you to throw the exception or Log in catch block
if ((uint)ce.ErrorCode == 0x800A03EC)
{
//DO LOGGING;
}
else
{
throw ce;
}
You have two different problems here. First, your catch block won't return anything if the condition is not met. Second, the return type within the catch block is not the same as the one inside of the try block.
You probably want something more like this in your catch block:
catch (COMException ce)
{
if ((uint)ce.ErrorCode == 0x800A03EC)
return null; // Don't return anything if a specific code was found
throw ce; // Rethrow the exception for all other issues.
}

Error Trapping Best Method

Hi I am trying to get a list of all trouble tickets but it says that not all codes paths return a value. Does Anybody no what I am doing wrong thanks
public List<TroubleTicket> GetAllTroubleTickets()
{
try
{
List<TroubleTicket> tickets = new List<TroubleTicket>();
var q = _supportDeskEntities.TroubleTickets.ToList();
return q;
}
catch (Exception ex)
{
}
}
If you catch an exception the function returns no value. So change this:
catch (Exception ex)
{
}
To this:
catch (Exception ex)
{
return null;
}
Or if you want it to return an empty list when an exception is catch then you can do this:
catch (Exception ex)
{
return new List<TroubleTicket>(0);
}
If we are taking about best practice then I would say that you should log the exception and then re-throw it. Like this:
catch (Exception ex)
{
//write to log
throw ex;
}
You need to return a value from the catch statement (or throw another exception within it). Otherwise, the function will return null
You can try this:
public List<TroubleTicket> GetAllTroubleTickets()
{
try
{
List<TroubleTicket> tickets = new List<TroubleTicket>();
var q = _supportDeskEntities.TroubleTickets.ToList();
return q;
}
catch (Exception ex)
{
return new List<TroubleTicket>(); // This is just in case you want to ignore any exceptions
}
}
or
catch (Exception ex)
{
throw new Exception("There was an error getting tickets"); // Probably not as good of a way as you lose the exception details
}
You only return a value if there is no exception thrown. You must either return from inside the catch block, or return outside the try/catch structure.
So you can either return in two separate places:
public List<TroubleTicket> GetAllTroubleTickets()
{
try
{
var q = _supportDeskEntities.TroubleTickets.ToList();
return q;
}
catch (Exception ex)
{
// You can also return "new List<TroubleTicket>()" if null is an unacceptable return value
return null;
}
}
or keep a return value variable, and set it in two different locations, and return it in one location:
public List<TroubleTicket> GetAllTroubleTickets()
{
List<TroubleTicket> tickets;
try
{
tickets = _supportDeskEntities.TroubleTickets.ToList();
}
catch (Exception ex)
{
// You can also use "new List<TroubleTicket>()" if null is an unacceptable return value
tickets = null;
}
return tickets;
}
You're not returning anything if an exception happens and you're not assigning the list to List<TroubleTicket> tickets but to a different variable. You could do:
public List<TroubleTicket> GetAllTroubleTickets()
{
List<TroubleTicket> tickets = null;
bool gotTickets = true;
try{
tickets = _supportDeskEntities.TroubleTickets.ToList();
}
catch (SpecificException ex){
gotTickets = false;
}
catch (Exception ex){ // catches all other "unexpected" exceptions
// log and/or...
throw;
}
return gotTickets ? tickets : null;
}
But you should not catch all kind of exceptions but only specific types that you expect. You also should log all other types of exceptions.
Your catch block is not returning anything.
public List<TroubleTicket> GetAllTroubleTickets()
{
List<TroubleTicket> tickets =null;
try
{
tickets = new List<TroubleTicket>();
var q = _supportDeskEntities.TroubleTickets.ToList();
return q;
}
catch (Exception ex)
{
//Log or handle your error
}
return tickets;
}

Not all code paths return a value sql

Error :'WinWithStudentDatabase.Broker.FillComboBox()': not all code
paths return a value.
I know what that error means but can not figure out why its not working :/ ... this is my code:
public List<Person> FillComboBox()
{
List<Person> personsList = new List<Person>();
try
{
string sql = "SELECT * FROM Tperson";
cmd = new SqlCommand(sql, connection);
connection.Open();
System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read() != null)
{
Person p = new Person();
p.Id = Convert.ToInt32(reader["ID"].ToString());
p.FirstName = reader["FirstName"].ToString();
p.LastName = reader["LastName"].ToString();
personsList.Add(p);
}
return personsList;
}
catch (Exception eX)
{
MessageBox.Show(eX.Message);
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
Any suggestions? im trying just to read data from my DB and fill combobox thats all..
You have declared your function to return a List<Person> but the catch block exits without returning anything
catch (Exception eX)
{
MessageBox.Show(eX.Message);
return null;
// or return an empty list if more appropriate
// return new List<Person>();
}
The compiler sees that you have coded a catch block meaning that you expect to handle an exception here. But when the catch block exits there should be a return value.
It is difficult to say what is the proper way to return in these situations. I personally prefer to return a null object and test for this in the calling code. (I avoid to return an eventually partially filled list declared at the start of the method)
A method that returns a value must have a return statement in all code paths.
In compile time, your program can't know your catch block will work or not. That's why you should add a return value inside your catch block also.
One solution could be;
catch (Exception eX)
{
MessageBox.Show(eX.Message);
return null;
}
For more information, take a look at Methods (C# Programming Guide)
Problem : if you are using return statement it should be able to return the values from all the code blocks.
Solution 1: so you need to either add it in catch block or at the end of the function.
remove the return statement return personsList; from try block and add it athe end of the function
Try This:
catch (Exception eX)
{
personsList = null;
}
finally
{
if (connection != null)
{
connection.Close();
}
}
return personsList;
OR
Add the return statement both in try and catch block
catch (Exception eX)
{
MessageBox.Show(eX.Message);
return null;
}

asp.net Passing name of method as parameter to another method

I tried to find answer how to use delegate for this example, but still I don't know how to use it for my code redundancy. I have this code which is repeated for each dbAction in my aplication:
public bool someDBMethod(params)
{
logDTO ldto = new logDTO("some text");
try
{
if (DALmethod(params)) //DB operation is successfull
{
Log.insertLog(ldto); //inserrt log to DB
return true;
}
catch (System.Data.SqlClient.SqlException ex)
{
Log.insertLog(changeLogStatus(ldto, errStatusEnum.ERR_SQL, ex.Message));
throw new Exception (ex.Message);
}
catch (Exception ex)
{
Log.insertLog(changeLogStatus(ldto, errStatusEnum.ERR, ex.Message));
throw new Exception (ex.Message);
}
}
This code is the same for different DB opperations except lines
logDTO ldto = new logDTO("some text");
if (DALmethod(params)) //DB operation is successfull
where I create DAL specific log and call the DAL method for insert/update/delete to database. Parameters for these DAL method aren't the same, but I could use some wrapper.
I would like to call for any DAL method
result = someDBMethod(DALmethod m, params p, logDTO l)
Thanks for your help
you could pass a Func<> as argument to your method.
public bool someDBMethod(Func<bool> callDalMethod, string message)
{
logDTO ldto = new logDTO(message);
try
{
if (callDallMethod()) //DB operation is successfull
{
Log.insertLog(ldto); //inserrt log to DB
return true;
}
catch (System.Data.SqlClient.SqlException ex)
{
Log.insertLog(changeLogStatus(ldto, errStatusEnum.ERR_SQL, ex.Message));
throw new Exception (ex.Message);
}
catch (Exception ex)
{
Log.insertLog(changeLogStatus(ldto, errStatusEnum.ERR, ex.Message));
throw new Exception (ex.Message);
}
Call this method:
someDBMethod(() => myDbMethod(param1, param 2), "message text");

What's wrong with this function. unable to return string value

public static string GetContentFromSPList(string cValueToFind)
{
string cValueFound = "";
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite("http://mysite"))
{
site.AllowUnsafeUpdates = true;
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList oListAbout = web.Lists["About"];
SPQuery oQuery = new SPQuery();
oQuery.Query = "<OrderBy><FieldRef Name='myField' /></OrderBy><Where><Eq><FieldRef Name='myField' /><Value Type='Choice'>" + cValueToFind + "</Value></Eq></Where>";
SPListItemCollection collListItems = oListAbout.GetItems(oQuery);
foreach (SPListItem oListItem in collListItems)
{
cValueFound = (oListItem["FieldContents"] != null ? oListItem["FieldContents"].ToString() : "");
}
}
}
return cValueFound;
});
//return cValueFound;
}
catch (Exception ex)
{
}
finally
{
//return cValueFound;
}
}
Above is the piece of code.
Problem is not allowing to return the string. It keeps on giving compilation errors. I am sure I am doing something wrong!!.
Thanks.
I suppose it's something like:
"not all codes return value".
If so, just add
public static string GetContentFromSPList(string cValueToFind)
{
string cValueFound = "";
try
{
//code
}
catch (Exception ex)
{
}
finally
{
//some cleanup
}
return cValueFound ;
}
Put this at the bottom of your method because you don't return if an exception is caught.
catch (Exception ex)
{
return cValueFound;
}
finally
{
}
}
You cannot return from finally,
(control cannot leave the body from finally clause or something)
move the return either after finally or from catch
just add your return statement below finally block.
Dont return in try blck.
I have seen developers missing this lot of times. Reason this happens is because once you define the return type of a function, then function should have a return statement at all exit points. In this case a function should have a return statement one at the end of the try block and one inside a catch block or just one right at the bottom as Tigran has defined. If you do not intend to return any thing from the catch block then just return null;
public static string GetContentFromSPList(string cValueToFind)
{
string value= "";
try
{
//code
return value;
}
catch (Exception ex)
{
return null;
}
finally
{
//some cleanup
}
}

Categories

Resources