How to handle a NullReference Exception c# - c#

I am trying to handle a NullReference Exception, but i am confused how to handle that. Here is my sample code where a NullReference exception is raised:
private Customer GetCustomer(string unformatedTaxId)
{
return loan.GetCustomerByTaxId(new TaxId(unformatedTaxId));
}
Now i am handling this in the following method
public void ProcessApplicantAddress(ApplicantAddress line)
{
try
{
Customer customer = GetCustomer(line.TaxId);
//if (customer == null)
//{
// eventListener.HandleEvent(Severity.Informational, line.GetType().Name, String.Format("Could not find the customer corresponding to the taxId '{0}' Applicant address will not be imported.", new TaxId(line.TaxId).Masked));
// return;
//}
Address address = new Address();
address.AddressLine1 = line.StreetAddress;
address.City = line.City;
address.State = State.TryFindById<State>(line.State);
address.Zip = ZipPlusFour(line.Zip, line.ZipCodePlusFour);
}
catch(NullReferenceException e)
{
//eventListener.HandleEvent(Severity.Informational, line.GetType().Name, String.Format("Could not find the customer corresponding to the taxId '{0}' Applicant address will not be imported.", new TaxId(line.TaxId).Masked));
eventListener.HandleEvent(Severity.Informational, line.GetType().Name, e.Message);
}
}
I the previous case i am writing like if(customer == null) now i should get rid of that code so that i can handle it in the catch block.
Please help me how to throw that exception.

I am trying to handle a NullReference Exception, but i am confused how
to handle that
Well you already have by checking if customer is null. You need that check in place.
Throwing an exception is expensive, and knowing that this exception can be caused if the TaxId is not valid is not really an exceptional case, it's a problem in validating the user input in my opinion.
If an object can return null, simply check that object's value before trying to access the properties/methods. I would never allow an exception to be thrown and interrupt the standard program flow just to catch an Exception and log it.

I'd do something like
public void ProcessApplicantAddress(ApplicantAddress line)
{
if (line == null)
{
eventListener.HandleEvent(Severity.Informational, line.GetType().Name, "a message");
throw new ArgumentNullException("line");
}
Customer customer = GetCustomer(line.TaxId);
if (customer == null)
{
eventListener.HandleEvent(Severity.Informational, line.GetType().Name, "a message");
throw new InvalidOperationException("a message");
}
Address address = new Address();
if (address == null)
{
eventListener.HandleEvent(Severity.Informational, line.GetType().Name, "a message");
throw new InvalidOperationException("a message");
}
address.AddressLine1 = line.StreetAddress;
address.City = line.City;
address.State = State.TryFindById<State>(line.State);
address.Zip = ZipPlusFour(line.Zip, line.ZipCodePlusFour);
}
The caller is responsable to handle exceptions and to validate args that sends.

Related

how to pass an error message back before an exception is thrown

i have the following code that gets an error message.i want to pass it into a string before an exception is thrown,this is my code
ValidateError(authDeserialized, "Succeed", "error", "failed"); //the validateError is a function as indicated below
Model.Response= authResponse.Content;
protected static void ValidateError(dynamic response, string validStatus,string categoryMatch, string message)
{
if (response.result.status != validStatus)
{
try
{
var category = response.result.category;
if (category == categoryMatch)
message=ErrorCodes.MessageFor(code,description);
//so i get the message back fine here but now how do i pass it back to this line Model.Response= authResponse.Content; so that it can get saved?
}
catch (Exception) { }
throw new Exception(message ?? "Request was not successfull");
}
}
As you are already sending message to the ValidateError() method, pass that parameter as a out parameter, it will update value of message if you assign new value to it then it will update message and will be accessible to outside environment.
string failureMessage = "failed";
ValidateError(authDeserialized, "Succeed", "error", out failureMessage);
//^^^ This is what you have to change
//Now you can assign failureMessage to any other value
Model.Response= authResponse.Content;
protected static void ValidateError(dynamic response, string validStatus,string categoryMatch, out string message)
{ //^^^ This is what you have to change
if (response.result.status != validStatus)
{
try
{
var category = response.result.category;
if (category == categoryMatch)
message=ErrorCodes.MessageFor(code,description); //so i get the message back fine here but now how do i pass it back to this line Model.Response= authResponse.Content; so that it can get saved?
}
catch (Exception) { }
throw new Exception(message ?? "Request was not successfull");
}
}
In this way you can assign value to failure message before throwing an error.
Try out online

Webservice object fail handling

I have a problem regarding try catch when creating an object in C#.
My problem appears when an object is supposed to be created and the webservice which defines the object isn't available or has been modified.
That is the problem I would like my program to handle.
When I try to do this:
try
{
var Customer = new Customer();
}
catch
{
//handling the exception.
}
Later on in my program I need that particular object, but due to the try catch the object isn't available in all cases (of course when the try fails, the object isn't created).
without if(customer != null)
if (insertCustomer(lead, LS_TS, out Customer) == true)
{
insert = true;
}
with if(customer != null)
if(customer != null)
{
if (insertCustomer(lead, LS_TS, out Customer) == true)
{
insert = true;
}
}
No matter what, the compiler says: "The name 'Customer' does not exist in the current context
How do I solve this problem? I need a program to be running all the time and when checking an object which isn't created then I need to exit the method and try again later.
Thanks in advance
You can just do this:
Customer customer = null;
try
{
customer = new Customer();
}
catch
{
// handling the exception.
}
and whenever you need to use the object customer you should do this
if(customer != null)
{
// do stuff
}

Unhandled runtime error c#

private void SetConnection(string id, string classCode)
{
try
{
_connection = new SqlConnection { ConnectionString = Settings.Default.CurrentConnection };
_connection.Open();
while (_connection.State == ConnectionState.Connecting || _connection.State == ConnectionState.Closed)
Thread.Sleep(1000);
_command = new SqlCommand(Settings.Default.EligibilityBenefitSP, _connection);
if (_command != null) _command.CommandType = CommandType.StoredProcedure;
_command.Parameters.Add("#ClassCode", SqlDbType.NVarChar).Value = classCode;
_command.Parameters.Add("#Id", SqlDbType.NVarChar).Value = id;
}
catch (Exception e)
{
throw new Exception(e.Message + " " + Settings.Default.EligibilityBenefitSP);
}
}
public Collection<EligibilityClassBenefit> ExtractEligibilityClassBenefit(string id, string classCode)
{
SetConnection(id, classCode);
Collection<EligibilityClassBenefit> eclassBene = new Collection<EligibilityClassBenefit>();
SqlDataReader reader = null;
try
{
_command.CommandTimeout = 420;
if (_connection.State == ConnectionState.Open)
reader = _command.ExecuteReader(CommandBehavior.CloseConnection);
else
throw new Exception("Connection Closed");
/* no data */
if (!reader.HasRows) return null;
while (reader.Read())
{
EligibilityClassBenefit eligibilityClassBenefit = new EligibilityClassBenefit
{
EffectiveDate = reader["EffectiveDate"].ToString(),
EndDate = reader["EndDate"].ToString(),
InitialEffectiveDate = reader["InitialEffectiveDate"].ToString(),
IsAdministrativeServicesOnly = reader["IsAdministrativeServicesOnly"].ToString(),
EffectiveProvision = reader["EffectiveProvision"].ToString(),
ProbationPeriod = reader["ProbationPeriod"].ToString(),
UnderwritingType = ExtractUnderwritingType(id),
ProbationPeriodUnit = reader["ProbationPeriodUnit"].ToString(),
StateOfIssue = reader["StateOfIssue"].ToString(),
};
BenefitData benefitData = new BenefitData();
eligibilityClassBenefit.Benefit = benefitData.ExtractBenefit(reader, id, classCode);
EligibilityClassBenefitBusinessLevelData eligibilityLevelData = new EligibilityClassBenefitBusinessLevelData();
eligibilityClassBenefit.EligibilityClassBenefitBusinessLevelNodes = eligibilityLevelData.ExtractBenefitBusinessLevel(reader);
eclassBene.Add(eligibilityClassBenefit);
}
return eclassBene;
}
catch (Exception e)
{
throw new Exception(e.InnerException.Message + e.InnerException.StackTrace);
}
finally
{
//if (_connection.State == ConnectionState.Open) _connection.Close();
if (reader != null) reader.Close();
_command.Dispose();
}
}
Above is an example of code that has a general exception catch in it, yet when i run this program, it will randomly break and thow and unhandled exception to the application log with a .net runtime error null reference exception.
A little background...this is a console application that runs automatically at midnight on an application server. It executes stored procedures against a different SQL Server 2008 box. We used to get these errors when the connections were dropped by the sql server when doing a mainenace task, that is no longer the case. I need to get a mmore specific error. I don't understand why its bypassing the catch clause and just throwing an unhandled runtime exception. What does this mean? It happens at any number of points of code, not just this one. this is just an example of the last that blew up
While you are catching exception, you are also throwing them out to be handled by the caller. Now, there is no entry point in the code you've posted so it's hard to see what's going on outside this snippet.
However, taking a wild guess, my suggestion for origin of the NullRef exception is where you do this: e.InnerException.Message.
The InnerException property may well be null and that will cause a NullRef exception. That, however, is not the real exception. The real exception, which caused the program to end up in the exception handler is hidden because of the above mistake.
If you want to include the message from the InnerException, first check if it's null or not.
EDIT:
Doing this:
catch (Exception e)
{
throw new Exception(e.InnerException.Message + e.InnerException.StackTrace);
}
Catches any exception and rethrows it out to be handled. If the calling code is not handling exceptions, ie not wrapped the call in a try-catch block, the exception will be treated as unhandled by the runtime.
Actually, there is no point at all to do what you are doing. Don't catch exceptions unless you intend to do something about the problem. What you do here is simply messing up the StackTrace for the caller since you are rethrowing a new exception. If you feel you have to cut in and rethrow for some reason, you should do this:
catch (Exception e)
{
throw new Exception("I have a good reason for interrupting the flow", e);
}
Note that the exception instance is passed in the constructor for the rethrown exception. That will end up as the inner exception.
About your exception strategy, this is also pretty unnecessary:
if (_connection.State == ConnectionState.Open)
reader = _command.ExecuteReader(CommandBehavior.CloseConnection);
else
throw new Exception("Connection Closed");
The ExecuteReader method already throws an InvalidOperationException if the connection is closed which is more specific than your throw of Exception. If you intend to do something about that, catch the more specific exception later on. Now, you're using exceptions as part of your program logic which is not good practice.

data type to use for an exception thrown by a validator?

I need to capture any exceptions thrown by the validator but I cannot figure out how to due it. Here is the code I have tried:
internal static class XMLValidator
{
public static void Validate(XElement elem)
{
string xsdMarkup;
using(var file = new StreamReader(Constants.Xsd))
{
xsdMarkup = file.ReadToEnd();
}
XmlSchemaSet schema = new XmlSchemaSet();
bool valid = true;
schema.Add(XmlSchema.Read(XElement.Parse(xsdMarkup).CreateReader(), (o, e) => { }));
new XDocument(elem).Validate(schema, (o, e) => { valid = false; exception = e; });
if (valid == false)
{
throw exception;
}
valid = true;
}
}
I get a "the name exception does not exist in current context" error. I'm pretty sure that the problem is that I have not given exception a data type. However I have no idea what type to use.
I tried adding var before the exception but then it's not recogonized inside of the if statement and of course var cannot be declared outside of a method
I then tried declaring exemption globally as a string and setting to e like this:
exception = e.ToString();
but then I can't throw it inside of the if statement.
How would I go about doing this?
The delegate you're using creates an XmlSchemaValidationException:
XmlSchemaValidationException exception = null;
new XDocument(elem).Validate(schema, (o, e) => { valid = false; exception = e.Exception; });
if (valid == false)
{
throw exception;
}
Well, in this particular case you probably want to create your own type of Exception to throw.
public class InvalidDataException : Exception
{ }
(There are times where it's appropriate to do something within the definition of the class, but in most cases you really don't need anything.)
Then you can do something like this:
throw new InvalidDataException("Error message goes here");
Or, you can find some existing type of exception to throw that is created by the standard library or what have you.

MVC - throwing exceptions but give message to say I must return a value from List

This is related to my other post. I am trying to add in some exception logic so I coded the following:
public IEnumerable<DrillFormat> List(string partitionKey)
{
try {
_drillServiceContext.MergeOption = MergeOption.NoTracking; // set when you will not be updating this entity
var results = from c in
_drillServiceContext.drillTable
where c.PartitionKey == partitionKey
select c;
var query = results.AsTableServiceQuery();
var queryResults = query.Execute();
return queryResults;
} catch (Exception e) {
System.Diagnostics.Trace.TraceInformation(e.Message
+ Environment.NewLine + e.StackTrace);
throw new Exception("Error while accessing the data store.", e);
}
}
but now I get a message saying that "not all code paths return a value". Does that mean I have to return a value even if I throw an exception?
If no exception is thrown this method will never return a value.
I usually put a return null or new List<DrillFormat>() in methods like this. Depends what the calling code expects and whether you want to handle null up the call chain.

Categories

Resources