krishna mohan
krishna mohan

Reputation: 267

how to handle null exception in C#

im getting null exception . while im directly exceciting this page. i want to handle null exception

C#

string json = "";
if (Request.QueryString["data"] !="")
{
    json = Request.QueryString["data"];

    var req = JsonConvert.DeserializeObject<Request>(json);//getting error in this line
    string requestid = req.requestId;
    SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MYSTRING"].ConnectionString);
    SqlCommand cmd = new SqlCommand();
    connection.Open();
}

error

Value cannot be null. Parameter name: value

Upvotes: 2

Views: 1801

Answers (4)

sujith karivelil
sujith karivelil

Reputation: 29016

You are getting such error when Request.QueryString["data"] is null. so you should check for null before using this value. in c# null cannot directly converted to String. Better method is suggested by john skeet.

 string json=Request.QueryString["data"];
 if(string.IsNullOrEmpty(json)){//Do your code;}

Upvotes: 0

Suprabhat Biswal
Suprabhat Biswal

Reputation: 3216

You can follow following two approach:-

Approach 1:

if (Request.QueryString["data"] != null && Request.QueryString["data"].toString() != string.Empty)
{
   .. Your Content Goes Here
}

Approach 2:

if (!string.IsNullOrEmpty(Request.QueryString["data"].toString()))
{
   .. Your Content Goes Here
}

Upvotes: 1

Mostafa Mohamed Ahmed
Mostafa Mohamed Ahmed

Reputation: 649

you can u string.isNullOrwhiteSpace() Method and it returns a bool ...true if the input is empty ...false if there is any characters

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500385

Well presumably Request.QueryString["data"] is null. You're currently checking whether it's a reference to an empty string, but not whether it's a null reference. I suspect you want to use string.IsNullOrEmpty to check that:

string json = Request.QueryString["data"];
if (!string.IsNullOrEmpty(json))
{
     var req = JsonConvert.DeserializeObject<Request>(json);
     ...
}

Upvotes: 5

Related Questions