views:

818

answers:

6

Hello,

I am trying to create an object from an Active Directory base on a simple login. The problem is that some of the login information is valid.

How could I just use a try-catch so that if an exception is thrown, just skip to the next login?

Here is the code:

foreach (var PharosUserItem in ListRef)
{
    ADUser User;
    try
    {
        User = new ADUser(PharosUserItem.UserLoginPharos);
    }
    catch (ByTel.DirectoryServices.Exceptions.UserNotFoundException ex)
    {
        break;
    }
}

The break gets me out of the foreach, which is not what I want. Any ideas?

+11  A: 

Use the continue statement instead:

foreach (var pharosUserItem in ListRef)
{
    ADUser user;
    try
    {
        user = new ADUser(pharosUserItem.UserLoginPharos);
    }
    catch (UserNotFoundException)
    {
        continue;
    }
    // Use "user" here
}

(I've made a few changes in terms of variable casing, avoiding using a massively long fully-qualified name for the exception, and providing a variable for the exception which you then ignore.)

Note that if there's any reasonable way that you could get a list of valid users and check it, that would be nicer than using the exception for flow control as you're doing here. It may not be feasible, but it's worth checking :)

Jon Skeet
+4  A: 

You have to use continue;

tanascius
+26  A: 

You are looking for continue

foreach (var PharosUserItem in ListRef)
    {
        ADUser User;
        try
        {
            User = new ADUser(PharosUserItem.UserLoginPharos);
        }
        catch (ByTel.DirectoryServices.Exceptions.UserNotFoundException ex)
        {
            continue;
        }
    }
Joseph
+4  A: 

Use the continue statement to skip to the next iteration.

TheTXI
+1  A: 

Rather than throwing an exception, instead you should try and check if the user is valid first. Throwing exceptions is quite expensive and should really only be used in 'exceptional' circumstances and not to control the logical flow of the app, this isn't what they should be used for as you are expecting some users to fail.

Simon P Stevens
A: 

why not use nothing instead of continue?

Use the continue statement instead:

foreach (var pharosUserItem in ListRef)
{
    ADUser user;
    try
    {
        user = new ADUser(pharosUserItem.UserLoginPharos);
    }
    catch (UserNotFoundException)
    {

    }
    // Use "user" here
}

or put a

       console.writeline("user not found: "+ pharosuseritem.tostring() );
Crash893