Hai,
In my code while executing a function i got regularly the exception error as "Object reference not set to an instance of an object"
The function exceuting is as follows
private void PageHeaderSetting(Graphics g)
{
try
{
DataTable dtPageHeader=new DataTable() ;
dtPageHeader = ds.Tables["Page Header"];
if (dtPageHeader.Rows.Count != 0)
{
foreach (DataRow dr in dtPageHeader.Rows)
{
if (dr.ItemArray[0].ToString() != "")
PageHeaderText = dr.ItemArray[0].ToString();
else
PageHeaderText = "";
if (dr.ItemArray[1].ToString() != "")
PageHeaderFont = (Font)dr.ItemArray[1];
else
PageHeaderFont = new Font("Tahoma", 18, FontStyle.Bold, GraphicsUnit.Point);
if (dr.ItemArray[2].ToString() != "")
PageHeaderFormat = AlignmentSetting(dr.ItemArray[2].ToString());
else
PageHeaderFormat = AlignmentSetting(Convert.ToString(Alignment.Left));
if (dr.ItemArray[3].ToString() != "")
PageHeaderColor = (System.Drawing.Color)dr.ItemArray[3];
else
PageHeaderColor = Color.Black;
PageFooterText = Word_Wrap(PageHeaderText, PageHeaderFont, g, 0);
PageHeader(g);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
How can i solve this.Can anybody help me?
From the second line i got the exception error
means after declaring the datatable and putting the ds.Tables in it from there erroe occurs
This exception means you're trying to call a method on a null object. The exception should have given you a stack trace with the line number it was thrown at; this'll help you pin it down a bit. You could also try debugging it in visual studio and see where the exception is thrown & see what is null.
Instead of using ToString() to check if you have a value in the ItemArray you should check the actual value. Check for ItemArray[0] == null and ItemArray[0] == DBNull.Value.
Edit:
From your comment it seems that there may not be any data table named "Page Header" in your data set.
Try to add a null check to your DataTable object after the line dtPageHeader = ds.Tables["Page Header"];
Something like this:
if (dtPageHeader == null)
{
// There is no table named Page Header
}
Look at the line number in the exception.
Your code has numerous chained calls, which is a common source of this exception. If either of these chained properties returns null, the "next" call in the chain will fail with a NullReferenceException.
One of this could be true:
ds is null
A Value on a columun in dtPageHeader is null
Related
So I'm using an if statement and I would assume if that statement doesn't find/do what it's suppose to, then it should throw an exception right? Well for some reason I'm getting absolutely nothing, the if statement isn't working, yet I'm not getting an exception?
Example of code -
try
{
label1.Text = "Finding route";
string sxp = "//*[#id='s']";
if (driver.FindElements(By.XPath("sxp")).Count != 0)
{
driver.FindElement(By.XPath(sxp)).Click();
label1.Text = "sxp done";
}
}
catch
{
CheckRoute();
label1.Text = "Exception thrown";
}
and the response from my program is nothing as soon as it hits the " if " statement, because before that it changes label1 to specified string..
Since you are checking it with if statement it has nothing to do with Exception throw. Remove if and it will throw an exception when it cant find the element. Also access the message with e.Message() if I am not mistaking. In your case it should be ElementNotFoundException.
try
{
label1.Text = "Finding route";
string sxp = "//*[#id='s']";
driver.FindElement(By.XPath(sxp)).Click();
label1.Text = "sxp done";
}
catch(Exception e)
{
CheckRoute();
label1.Text = "Exception thrown";
}
catch(ElementNotFoundException e)
{
Console.WriteLine(e.Message());
}
I think you are confused about ifs and how they work. ifs don't throw exceptions if they don't evaluate to true. Exceptions are thrown in specific cases when something unexpected happens. On example would be if you used driver.FindElement() and the element wasn't found... that would throw an ElementNotFoundException.
In your case, you have done the right thing and used .FindElements() (plural) and because of this, your code will not throw an exception. So, because of this you can remove the try-catch and additional simplifications result in the code below.
label1.Text = "Finding route";
IReadOnlyCollection<IWebElement> routes = driver.FindElements(By.Id("s"));
if (routes.Count > 0)
{
routes.ElementAt(0).Click();
label1.Text = "sxp done";
}
else
{
CheckRoute();
label1.Text = "sxp not found";
}
I stored the resulting collection from the .FindElements() in a variable, routes, so that it can be reused. Your code was hitting the page twice. I removed the try-catch because it was not needed.
Regarding the duplicated. I can access the Message property but not the Detail property even when I can see is part of the Exception object during debuging. So the question is Why cant access Detail property.
I catch an exception.
catch (Exception ex)
{
string msg = ex.InnerException.InnerException.Message;
// say Exception doesnt have Detail property
// string detail = ex.InnerException.InnerException.Detail;
return Json(new { status = "Fail", message = msg, detail: detail });
}
ex doesnt say anthing
ex.InnerException show same message
ex.InnerException.InnerException. finally some real message, "db table duplicated key"
ex.InnerException.InnerException.Message I can get the message.
But cant get the Detail "the guilty key" even when there is one property Detail
So how can I get the Detail?.
Bonus: Why have to go deep InnerException twice to get some meaningfull message?
I think the most elegant way to do this now is using C# 6 when keyword in a catch statement and C# 7 is operator.
try
{
//your code
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException pex)
{
string msg = pex.Message;
string detail = pex.Detail;
return Json(new { status = "Fail", message = msg, detail: detail });
}
The trick is to recognize the type of exception being thrown and cast the General Exception to the correct Type where you will then have access to extended properties for that Exception type.
for example:
if (processingExcption is System.Data.Entity.Validation.DbEntityValidationException)
{
exceptionIsHandled = true;
var entityEx = (System.Data.Entity.Validation.DbEntityValidationException)processingExcption;
foreach (var item in entityEx.EntityValidationErrors)
{
foreach (var err in item.ValidationErrors)
returnVal.Invalidate(SystemMessageCategory.Error, err.ErrorMessage);
}
}
else if (processingExcption is System.Data.SqlClient.SqlException && ((System.Data.SqlClient.SqlException)processingExcption).Number == -2)//-2 = Timeout Exception
{
exceptionIsHandled = true;
returnVal.Invalidate(SystemMessageCategory.Error, "Database failed to respond in the allotted time. Please retry your action or contact your system administrator for assistance.",
messageCode: Architecture.SystemMessage.SystemMessageCode.DBTimeout);
}
The fact that the detail you are looking for is 2 inner exceptions deep is incidental. Depending on how many times the exception is caught and wrapped will determine how deep the exception you care about is - your best bet is to iterate through the exception stack looking for exception types you wish to handle.
Referring to your own answer I commented, you definitely should be much more defensive, otherwise you risk of a null reference exception from within your catch clause.
catch (Exception ex)
{
string Detail = string.Empty;
while ( ex != null )
{
if ( ex is Npgsql.NpgsqlException )
{
// safe check
Npgsql.NpgsqlException ex_npg = (Npgsql.NpgsqlException)ex;
Details = ex_npg.Detail;
}
// loop
ex = ex.InnerException;
}
// warning, Detail could possibly still be empty!
return Json(new { status = "Fail", detail = Detail });
}
You cannot get details more than found in this exception
To show real exception loop over innerexceptions until it is null. Then you reached the first one
The exception was thrown from a source class or function then readed by upper level class that throw it with more global details because there is no error handling on the source
Well, it's very sad, but the inner exception is not a magic stick. Usually it's just an object that author of the code that you call puts as the second parameter of the Exception constructor. So, the general answer: "no way". But debugger sometimes could help :). I would say - call stack of the exception usually more descriptive the InnerException.
A quick solution would be to click on the "Detail" property in the "Quick Watch" window. Your answer will be in "Expression" texbox at the top of the quick watch window. Example, the expression for Postgres duplicate detail is:
((Npgsql.PostgresException)ex.InnerException.InnerException).Detail
Here is my function to get some more info from Postgres exception
catch (Exception ex) {
// Get PGSQL exception info
var msg = ExceptionMessage (ex);
}
public static string ExceptionMessage (Exception ex) {
string msg = ex.Message;
var pgEx = ex as PostgresException;
if (pgEx != null) {
msg = pgEx.Message;
msg += pgEx.Detail != null ? "\n"+pgEx.Detail.ToStr() : "";
msg += pgEx.InternalQuery != null ? "\n"+pgEx.InternalQuery.ToStr() : "";
msg += pgEx.Where != null ? "\n"+ pgEx.Where : "";
}
return msg;
}
Thanks Maciej
this solution is great to intercept PostgreSQL Errors
Only correction I did on this
msg += pgEx.Detail != null ? "\n"+pgEx.Detail.ToStr() : "";
msg += pgEx.InternalQuery != null ? "\n"+pgEx.InternalQuery.ToStr() : "";
instead
msg += pgEx.Detail != null ? "\n" + pgEx.Detail.ToString() : "";
msg += pgEx.InternalQuery != null ? "\n" + pgEx.InternalQuery.ToString() : "";
I'm compiling a program which was originally build in Visual C# 2005. I'am using visual C# 2010. And I keep getting "NullReference Execption was unhandled" errors when running the program on the following functions:
The error occurs on the line with DataBuffer. DataBuffer is an private string set to null on initialisation.
if (DataBuffer.Contains(ok))
{
okFound = true;
}
and
string temp = getLine(DataBuffer.Substring(mylocation));
if (!checkTypeFound())
{
if (temp != null)
{
parseDeviceType(temp);
}
checkTypeFound();
}
When I check what the value of DataBuffer is in the code above (when I get the error) this is not null. It actually contains the data I expect.
DataBuffer information is loaded in this function:
private void ser1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
while (ser1.BytesToRead > 0)
{
string data = ser1.ReadExisting();
DataBuffer += data;
}
}
The serial port is opened somewhere else in the code. There have been no changes to the code only the compiler is different. What line should I add, and where to solve this error? Note, I can prevent this error from happening using an if and try-catch statement. But this is not what I'm looking for, I need this code to work.
This application has not been changed in any way other than the compiler.
You should check if DataBuffer is null before you call its methods.
if (DataBuffer != null && DataBuffer.Contains(ok))
{
okFound = true;
}
// or simpler:
okFound = (DataBuffer != null && DataBuffer.Contains(ok));
and your second code snipped should check for null as well.
string temp = String.Empty;
if (DataBuffer != null)
temp = getLine(DataBuffer.Substring(mylocation));
if (!checkTypeFound())
{
if (!String.IsNullOrEmpty(temp))
parseDeviceType(temp);
checkTypeFound();
}
Try using the following:
if (DataBuffer != null && DataBuffer.Contains(ok))
{
okFound = true;
}
You should set the value of DataBuffer to something other than null in your constructor. If you can't do that then you may set it to string.Empty instead of null to avoid null exception. But it always better to check for null before initiating an instance method on object.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is a NullReferenceException in .NET?
Object reference not set to an instance of an object.
protected void Page_Load(object sender, EventArgs e)
{
int Role = Convert.ToInt32(Request.QueryString["Role"].ToString());
try
{
if (Role != 3)
{
gv_ViewApplicants.Visible = true;
gv_ViewApplicants_SelectedIndexChanged(this, new EventArgs());
}
else
{
gv_ViewApplicants.Visible = false;
}
}
catch (NullReferenceException e1)
{
}
}
Try
int Role = Convert.ToInt32(Request.QueryString["Role"] != null ?
Request.QueryString["Role"].ToString() :
"0");
instead of
int Role = Convert.ToInt32(Request.QueryString["Role"].ToString());
You need to check for null if not passed query string.
first thing
int Role = Convert.ToInt32(Request.QueryString["Role"].ToString());
This statement is outside try so if it crashes on QueryString being null or even if Convert.ToInt32 method throw exception, catch block will not be executed.
You can try this code
int number;
bool result = Int32.TryParse(Request.QueryString["Role"], out number);
if (result)
{
// your implemntation
}
else
{
// your implemntation
}
You can even use Convert.ToString(Request.QueryString["Role"]) if still u are getting this error.
The code is trying to access a member of a reference type variable that is set to null.
Please make source Request.QueryString["Role"] is not null.
You should Never catch NullReferenceException.
However, the problem seems to be in very first line: (the only line outside try block)
int Role = Convert.ToInt32(Request.QueryString["Role"].ToString());
either Request is null OR QueryString["Role"] is returning null.
Share the stack trace for more clear answer.
So I took over this project and one page is throwing a lot of errors. I would need to refactor the whole thing but as always time is an issue.
In one case the code check's whether a datareader has any rows and if not go to an error page. However as the code is now the datareader can be null (didn't successfully connect to db) and in those cases I can't use
if (!dr.HasRows)
//
becasuse it obviously gives me 'nullreferenceexception was unhandled by code'. I tried with !dr.Read but same thing.
A part of the code is something like
SqlDataReader dr = null;
try
{
//connect to db etc
dr = DbHelper.GetReader("sp_GetCustomer", param);
}
catch
{
//show an error message
}
// and then:
if (!dr.HasRows)
{
}
Any suggestions?
Thanks in advance.
What about:
if (dr == null || !dr.HasRows) {
// Do something
}
One possibility is:
SqlDataReader dr = null;
try
{
//connect to db etc
dr = DbHelper.GetReader("sp_GetCustomer", param);
if (!dr.HasRows)
{
}
}
catch
{
//show an error message
}