Should I use a "try-catch" to identify if a password is wrong?

9

In the login screen, I check the bank with select , and I'm using catch to catch this exception.

Is it correct to use catch for this type?

if (Usuario != string.Empty && Password != string.Empty)
        {
            try
            {
                consql._sql = @"SELECT id_usu FROM login WHERE usuario = @usuario AND password = @password";
                //consql._sql = @"SELECT COUNT(id_usu) FROM login WHERE usuario = @usuario AND password = @password";
                SqlCommand cmd1 = new SqlCommand(consql._sql, sqlconn);
                cmd1.Parameters.Add("@usuario", SqlDbType.VarChar).Value = Usuario;
                cmd1.Parameters.Add("@password", SqlDbType.VarChar).Value = Password;
                sqlconn.Open();
                int count_id = (int)cmd1.ExecuteScalar();

                if (count_id > 0)
                {
                    Sessaosistema.UsuarioId = count_id;
                    Sessaosistema.NomeUsuario = Usuario;

                    MessageBox.Show("Usuario logado com sucesso", "Login", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    Menu_Inicial mi = new Menu_Inicial();
                    mi.Show();
                    this.Hide();
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Usuário ou Senha incorretos" + "\n" + "Revise os dados inseridos e tente novamente", "Falha de Logon", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                sqlconn.Close();
            }
        }
    
asked by anonymous 21.07.2016 / 16:04

4 answers

19

If you have a memory allocation problem, the user, and therefore you, will receive a message saying "Incorrect User or Password". Do you think this is right?

If the database stops working, it will inform you that the password is wrong. Is it what you want?

If you have several other types of exceptions throughout the code - say that you do too much and mix up responsibilities - including programming errors , you want the user to be notified that the password Is it wrong?

Capturing Exception is almost always an error .

In fact, from what I understood the code, the exception has nothing to do with user error and password, which determines if the password is wrong is the count_id > 0 condition, ie if this is false, the password is wrong. Using the exception does not make the slightest sense. It almost always does not, especially to control normal flow of code, where if is more appropriate.

It's best to take this exception, maybe a more specific one elsewhere make some sense and use using in sqlconn .

    
21.07.2016 / 16:17
4

The Try/Catch most used to catch some error of exception in the system type problem of conversion these things.

My suggestion is that you check the count of the search in the database. If it returns 0, there is no user. This displays the "Incorrect User or Password" message, and leaving try and catch to syntax bug same.

    
21.07.2016 / 16:15
2

Let's get to the understanding of Exceptions and Try Catch!

Firstly, answering your question, yes I think you can and should use try catch to catch the password error, however with a question, before you create a correct Exception for this:

public class LoginPassInvalidException : Exception
{
    public LoginPassInvalidException() : base("Login ou Senha Inválidos!")
    {
    }

    public LoginPassInvalidException(string message) : base(message)
    {
    }

    public LoginPassInvalidException(string message, Exception innerException) : base(message, innerException)
    {
    }

    protected LoginPassInvalidException(SerializationInfo info, StreamingContext context) : base(info, context)
    {
    }
}

Then do the correct exception handling in the case: LoginPassInvalidException !!!

For better performance, use this way:

        try
        {
            consql._sql = @"SELECT id_usu FROM login WHERE usuario = @usuario AND password = @password";
            //consql._sql = @"SELECT COUNT(id_usu) FROM login WHERE usuario = @usuario AND password = @password";
            SqlCommand cmd1 = new SqlCommand(consql._sql, sqlconn);
            cmd1.Parameters.Add("@usuario", SqlDbType.VarChar).Value = Usuario;
            cmd1.Parameters.Add("@password", SqlDbType.VarChar).Value = Password;
            sqlconn.Open();
            int count_id = (int)cmd1.ExecuteScalar();

            if (count_id > 0)
            {
                Sessaosistema.UsuarioId = count_id;
                Sessaosistema.NomeUsuario = Usuario;

                MessageBox.Show("Usuario logado com sucesso", "Login", MessageBoxButtons.OK, MessageBoxIcon.Information);

                Menu_Inicial mi = new Menu_Inicial();
                mi.Show();
                this.Hide();
            }
            else
            {
                throw new LoginPassInvalidException();
            }
        }
        catch (LoginPassInvalidException ex)
        {
              MessageBox.Show(ex.Message + "\n" + "Revise os dados inseridos e tente novamente", "Falha de Logon", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Prezado usuário ocorreu uma ação não prevista, informe ao administrador do sistema: " + ex.Message, "Ação não prevista", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            sqlconn.Close();
        }

In short, programmers generally do not use Exceptions as a feature that can be programmed, but the right thing is to create the Exceptions for each error in your system and treat them as well as the framework itself!

    
22.07.2016 / 16:01
2

From what I saw in your code, I think it would be nice to use try/catch with the intention of catching the exception if the connection to the database is not established, so you can display a message on the screen to the user informing it.

    
22.07.2016 / 15:09