0

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

5
  • 1
    "then I need to exit the method" - return;? Commented Feb 11, 2016 at 12:07
  • No that's not my problem. try { var Customer = new Customer(); } catch { //handling the exception. } customer.Name= 'name of customer'; Compiler says: "The name 'customer' does not exist in the current context. Commented Feb 11, 2016 at 12:18
  • out Customer try this lowercase, like out customer Commented Feb 11, 2016 at 16:07
  • Also, are all this pieces of code in the same function? Or are they different functions? Commented Feb 11, 2016 at 16:12
  • Sorry for that. Ment Customer.Name= ... Commented Feb 12, 2016 at 14:51

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

As I see this, your answer only works without the try catch. The compiler won't accept use of the customer object other places than the try {xxx}
That is very weird. What is the error the compiler is giving you?
I put more code in the initial display. Please have a look there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.