Results 1 to 15 of 15

Thread: How to STOP program when catch an error?

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Apr 2017
    Location
    Washington DC
    Posts
    154

    How to STOP program when catch an error?

    Code:
    OdbcConnection Cn; 
    Username = txtUsername.Text;
    Password = txtPassword.Text;
    ConnectionString = "Driver={Adaptive Server Enterprise};server=*****;port=*****;db=*****;uid=" + Username + ";pwd=" + Password + ";";
    
    
    Cn = new OdbcConnection(ConnectionString);
                
    try
    {
    Cn.Open();
    }
    catch
    {
    MessageBox.Show("Invalid Username/Password.");
    }
    
    MessageBox.Show("Message after catch");
    If I run above code with correct username/password, then it displays one message box "Message after catch", which acts what I want.

    But if I run above code with wrong username/password, then it displays both message boxes, which is NOT what I want. I want the program to stop running after display "Invalid Username/Password", and let user to re-enter username/password.

    Thanks.
    Attached Images Attached Images   

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,297

    Re: How to STOP program when catch an error?

    You want to do the same thing multiple times? Isn't that what loops are for? You want to do the same thing while/until a particular condition is true/false? What type of loop is intended for that purpose?

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Apr 2017
    Location
    Washington DC
    Posts
    154

    Re: How to STOP program when catch an error?

    Quote Originally Posted by jmcilhinney View Post
    You want to do the same thing multiple times? Isn't that what loops are for? You want to do the same thing while/until a particular condition is true/false? What type of loop is intended for that purpose?
    Technically, this is what I would like to accomplish:
    1) If username/password is correct, then switch to another form FormInterface;
    2) If username/password is wrong, stay in current form FormLogin, don't do anything after displaying "Invalid Username/Password";

    So far, I use messagebox Message after catch to substitute switching to FormInterface, since I have not figured out how to switch form.

    What happen if multiple users connect to ODBC dababase via this exe file (put in a shared folder)? Does this kind of exe file allow multiple users to connect to database at the same time?

    Thanks.
    Last edited by VAian; Feb 28th, 2019 at 07:01 PM.

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,297

    Re: How to STOP program when catch an error?

    Quote Originally Posted by VAian View Post
    Technically, this is what I would like to accomplish:
    1) If username/password is correct, then switch to another form FormInterface;
    2) If username/password is wrong, stay in current form FormLogin, don't do anything after displaying "Invalid Username/Password";

    So far, I use messagebox Message after catch to substitute switching to FormInterface, since I have not figured out how to switch form.
    I've told you what to do: use an appropriate loop. If you know how loops work, that should be fairly easy. If you don't know how loops work, it's time to learn/review.
    Quote Originally Posted by VAian View Post
    TWhat happen if multiple users connect to ODBC dababase via this exe file (put in a shared folder)? Does this kind of exe file allow multiple users to connect to database at the same time?
    That's nothing to do with the topic of this thread.

  5. #5

    Thread Starter
    Addicted Member
    Join Date
    Apr 2017
    Location
    Washington DC
    Posts
    154

    Re: How to STOP program when catch an error?

    Quote Originally Posted by jmcilhinney View Post
    I've told you what to do: use an appropriate loop. If you know how loops work, that should be fairly easy. If you don't know how loops work, it's time to learn/review.

    That's nothing to do with the topic of this thread.
    To my understanding, loop is more about recurrence, it is like going through many sets of username/password. For my case, it only goes through one set of username/password, if you tell me to use IF statement, that could make more sense to me. But IF is almost duplicate to TRY here.

  6. #6
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,297

    Re: How to STOP program when catch an error?

    Quote Originally Posted by VAian View Post
    To my understanding, loop is more about recurrence
    That part of your understanding is correct and that is why you need to use a loop. This is what you said:
    I want the program to stop running after display "Invalid Username/Password", and let user to re-enter username/password.
    How is that not recurrence?
    Quote Originally Posted by VAian View Post
    it is like going through many sets of username/password.
    Loops in general are about performing an action multiple times. That's it, that's all. There are four different types of loops in C#: 'for', 'foreach', 'do' and 'while'. Maybe there are different types of loops because they each do different things. Do the appropriate reading to learn how each type of loop works and then choose the appropriate loop for your scenario.

    That's now three times that I have told you to use a loop. There will not be a fourth. If you make a genuine attempt to implement a loop and have issues then I'll be happy to help further. If you want to argue further why a loop shouldn't be required, you won't be talking to me.

  7. #7

    Thread Starter
    Addicted Member
    Join Date
    Apr 2017
    Location
    Washington DC
    Posts
    154

    Re: How to STOP program when catch an error?

    Quote Originally Posted by jmcilhinney View Post

    How is that not recurrence?
    No No No, re-enter username/password, then click button Connect, then re-run the whole application from the beginning, it is still going through one set of username/password only, nothing to do with loop. Assuming you are entering username/password to access your online banking account, if the username/password is wrong, then the system will return message "Invalid username/password" and stop, then you re-enter username/password, the system will treat this set of username/password independently, if it is correct, it will bring you to your account page, if it is still wrong, you will stay at the login page. As long as the system detects invalid username/password, then the program stops. When you re-enter another set of username/password, the program will run again from the beginning, from the first line of code (associating with button Connect).

    Maybe I need to add one line of code return; right below MessageBox.Show("Invalid Username/Password.");
    Last edited by VAian; Feb 28th, 2019 at 07:43 PM.

  8. #8
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,297

    Re: How to STOP program when catch an error?

    OK, I seem to have misunderstood the intention here. My apologies for that, but I'm not sure that your explanation makes complete sense. There's no stopping of the program and no re-running it. The program is running the whole time.

    Anyway, with my newfound understanding, it sounds like all you want is a Boolean condition you can test after that try/catch block. You already have one: whether or not the State of the connection object is Open. If you successfully opened the connection then clearly the credentials were valid. The problem arises if the connection is not opened successfully. Invalid credentials is just one of the possible reasons for that, even if it is the most likely. You really ought to distinguish between invalid credentials being the specific reason for the failure and other reasons. The exception itself can help you do that.

  9. #9

    Thread Starter
    Addicted Member
    Join Date
    Apr 2017
    Location
    Washington DC
    Posts
    154

    Re: How to STOP program when catch an error?

    Quote Originally Posted by jmcilhinney View Post
    OK, I seem to have misunderstood the intention here. My apologies for that, but I'm not sure that your explanation makes complete sense. There's no stopping of the program and no re-running it. The program is running the whole time.

    Anyway, with my newfound understanding, it sounds like all you want is a Boolean condition you can test after that try/catch block. You already have one: whether or not the State of the connection object is Open. If you successfully opened the connection then clearly the credentials were valid. The problem arises if the connection is not opened successfully. Invalid credentials is just one of the possible reasons for that, even if it is the most likely. You really ought to distinguish between invalid credentials being the specific reason for the failure and other reasons. The exception itself can help you do that.
    I am new, sorry that I could not use accurate term to clearly explain my question.

    In VBA, take the above code for example, the logic(what I want) will be something like below, I want something like Exit Sub. I am just talking about logic, not VBA syntax, I cannot guaranteed I have written VBA code correctly.

    My whole question is more about turning this logic into C# code.

    Code:
    OdbcConnection Cn; 
    Username = txtUsername.Text;
    Password = txtPassword.Text;
    ConnectionString = "Driver={Adaptive Server Enterprise};server=*****;port=*****;db=*****;uid=" + Username + ";pwd=" + Password + ";";
    
    
    Cn = new OdbcConnection(ConnectionString);
                
    On Error GoTo LoginErrorHandler
    Cn.Open();
    Cn.Close();
    
    'Then here is the code the switch to another form
    
    LoginErrorHandler:
    MsgBox "Invalid Username/Password."
    Exit Sub
    Last edited by VAian; Feb 28th, 2019 at 08:21 PM.

  10. #10
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,297

    Re: How to STOP program when catch an error?

    In C# there are no subs and functions. Every method is a function and the way to end a function is with a 'return' statement. So, test the State of the connection and, if it's not Open, return.

  11. #11
    PowerPoster kfcSmitty's Avatar
    Join Date
    May 2005
    Posts
    2,248

    Re: How to STOP program when catch an error?

    Could you not just do this?

    Code:
    OdbcConnection Cn; 
    Username = txtUsername.Text;
    Password = txtPassword.Text;
    ConnectionString = "Driver={Adaptive Server Enterprise};server=*****;port=*****;db=*****;uid=" + Username + ";pwd=" + Password + ";";
    
    
    Cn = new OdbcConnection(ConnectionString);
                
    try
    {
    Cn.Open();
    MessageBox.Show("Login successful!");
    }
    catch
    {
    MessageBox.Show("Invalid Username/Password.");
    }
    ?

    This will try to open the connection, and if it is succeeds, then it will say "Login Sucessful" but if the connection errors out with an exception, then it will say "Invalid Username/Password". Assuming this is being done in a button's click handler, then the form new form would simply not show and the user could enter their username/password again.

    However, doing a general try/catch is considered bad practice because you can't be sure you're only catching what you expect. For example, if you open the form after Cn.Open, and an exception is thrown there, a user would get prompted with "Invalid Username/Password" from your application. It would be best to change it from "catch" to

    Code:
    catch (OdbcException ex)

  12. #12

    Thread Starter
    Addicted Member
    Join Date
    Apr 2017
    Location
    Washington DC
    Posts
    154

    Re: How to STOP program when catch an error?

    Quote Originally Posted by kfcSmitty View Post
    Could you not just do this?

    Code:
    OdbcConnection Cn; 
    Username = txtUsername.Text;
    Password = txtPassword.Text;
    ConnectionString = "Driver={Adaptive Server Enterprise};server=*****;port=*****;db=*****;uid=" + Username + ";pwd=" + Password + ";";
    
    
    Cn = new OdbcConnection(ConnectionString);
                
    try
    {
    Cn.Open();
    MessageBox.Show("Login successful!");
    }
    catch
    {
    MessageBox.Show("Invalid Username/Password.");
    }
    ?

    This will try to open the connection, and if it is succeeds, then it will say "Login Sucessful" but if the connection errors out with an exception, then it will say "Invalid Username/Password". Assuming this is being done in a button's click handler, then the form new form would simply not show and the user could enter their username/password again.

    However, doing a general try/catch is considered bad practice because you can't be sure you're only catching what you expect. For example, if you open the form after Cn.Open, and an exception is thrown there, a user would get prompted with "Invalid Username/Password" from your application. It would be best to change it from "catch" to

    Code:
    catch (OdbcException ex)
    I understand the new form will not show here, so I used comment to omit that part of code, since I have not figured out how to write code to switch form, that is a different topic in another thread: http://www.vbforums.com/showthread.p...rms&highlight=

    This thread is not about switching form.

    Let me try to explain as clearly as possible: I have a FormLogin, user can enter username/password, if the set of username/password can open the database, then program can assure that it is correct username/password, then program will close FormLogin and show another form (but for this part of code, I have not figured it out yet, that is a topic in another thread, I am not asking that question in this thread) ; if the set of username/password cannot open database, the program can assume that it is invalid username/password, since developer is sure that the connection string is correct. If it is invalid username/password, then return message "Invalid username/password" and end the program within this button click.

  13. #13
    coder. Lord Orwell's Avatar
    Join Date
    Feb 2001
    Location
    Elberfeld, IN
    Posts
    7,621

    Re: How to STOP program when catch an error?

    since you are coming from vba maybe it would help you for me to tell you why your original code was throwing two popups. The way the try-catch works is that you are telling the compiler you will be manually handling the error. You may or may not know this. What you evidently don't know is that a try block works as though it is a gosub. After the code in the brackets completes, the next code after the closing bracket is ran. In this case that is your second popup so a failure would show both of them. Since you are preventing the error from stopping your program by catching it, you will always run that second popup. This is why kfcsmitty moved the call to your second popup. That fixed your logic. If cn.open fails, the next line of code that is ran is in the catch block and after the catch block is ran, there is no other code outside of the brackets. If cn.open succeeds the catch block will not run and the next line of code ran will be the success popup. I would suggest, based on your desired usage, that you set a variable equal to whether or not you succeed inside the try block. That way, you won't have the problem of an error in your other form returning to this one and triggering the catch block. Errors travel up the stack to the first available error handler. I suggest something like this:
    Code:
    OdbcConnection Cn; 
    Username = txtUsername.Text;
    Password = txtPassword.Text;
    ConnectionString = "Driver={Adaptive Server Enterprise};server=*****;port=*****;db=*****;uid=" + Username + ";pwd=" + Password + ";";
    
    
    Cn = new OdbcConnection(ConnectionString);
    bool SuccessfulConnection = false;            
    try
    {
    Cn.Open();
    SuccessfulConnection = true;
    }
    catch
    {
    MessageBox.Show("Invalid Username/Password.");
    }
    if (SuccessfulConnection == true)
    {
    //place form code here perhaps?
    MessageBox.Show("Login successful.");
    }
    This will prevent odd behavior from calling the external form from within a try block.
    My light show youtube page (it's made the news) www.youtube.com/@artnet2twinkly
    Contact me on the socials www.facebook.com/lordorwell

  14. #14
    coder. Lord Orwell's Avatar
    Join Date
    Feb 2001
    Location
    Elberfeld, IN
    Posts
    7,621

    Re: How to STOP program when catch an error?

    since you are coming from vba maybe it would help you for me to tell you why your original code was throwing two popups. The way the try-catch works is that you are telling the compiler you will be manually handling the error. You may or may not know this. What you evidently don't know is that a try block works as though it is a gosub. After the code in the brackets completes, the next code after the closing bracket is ran. In this case that is your second popup so a failure would show both of them. Since you are preventing the error from stopping your program by catching it, you will always run that second popup. This is why kfcsmitty moved the call to your second popup. That fixed your logic. If cn.open fails, the next line of code that is ran is in the catch block and after the catch block is ran, there is no other code outside of the brackets. If cn.open succeeds the catch block will not run and the next line of code ran will be the success popup. I would suggest, based on your desired usage, that you set a variable equal to whether or not you succeed inside the try block. That way, you won't have the problem of an error in your other form returning to this one and triggering the catch block. Errors travel up the stack to the first available error handler. I suggest something like this:
    Code:
    OdbcConnection Cn; 
    Username = txtUsername.Text;
    Password = txtPassword.Text;
    ConnectionString = "Driver={Adaptive Server Enterprise};server=*****;port=*****;db=*****;uid=" + Username + ";pwd=" + Password + ";";
    
    
    Cn = new OdbcConnection(ConnectionString);
    bool SuccessfulConnection = false;            
    try
    {
    Cn.Open();
    SuccessfulConnection = true;
    }
    catch
    {
    MessageBox.Show("Invalid Username/Password.");
    }
    if (SuccessfulConnection == true)
    {
    //place form code here perhaps?
    MessageBox.Show("Login successful.");
    }
    This will prevent odd behavior from calling the external form from within a try block.
    My light show youtube page (it's made the news) www.youtube.com/@artnet2twinkly
    Contact me on the socials www.facebook.com/lordorwell

  15. #15

    Thread Starter
    Addicted Member
    Join Date
    Apr 2017
    Location
    Washington DC
    Posts
    154

    Re: How to STOP program when catch an error?

    Quote Originally Posted by Lord Orwell View Post
    since you are coming from vba maybe it would help you for me to tell you why your original code was throwing two popups. The way the try-catch works is that you are telling the compiler you will be manually handling the error. You may or may not know this. What you evidently don't know is that a try block works as though it is a gosub. After the code in the brackets completes, the next code after the closing bracket is ran. In this case that is your second popup so a failure would show both of them. Since you are preventing the error from stopping your program by catching it, you will always run that second popup. This is why kfcsmitty moved the call to your second popup. That fixed your logic. If cn.open fails, the next line of code that is ran is in the catch block and after the catch block is ran, there is no other code outside of the brackets. If cn.open succeeds the catch block will not run and the next line of code ran will be the success popup. I would suggest, based on your desired usage, that you set a variable equal to whether or not you succeed inside the try block. That way, you won't have the problem of an error in your other form returning to this one and triggering the catch block. Errors travel up the stack to the first available error handler. I suggest something like this:
    Code:
    OdbcConnection Cn; 
    Username = txtUsername.Text;
    Password = txtPassword.Text;
    ConnectionString = "Driver={Adaptive Server Enterprise};server=*****;port=*****;db=*****;uid=" + Username + ";pwd=" + Password + ";";
    
    
    Cn = new OdbcConnection(ConnectionString);
    bool SuccessfulConnection = false;            
    try
    {
    Cn.Open();
    SuccessfulConnection = true;
    }
    catch
    {
    MessageBox.Show("Invalid Username/Password.");
    }
    if (SuccessfulConnection == true)
    {
    //place form code here perhaps?
    MessageBox.Show("Login successful.");
    }
    This will prevent odd behavior from calling the external form from within a try block.
    Thanks for your suggestion, I think your code will act same as below code. It is Form Login, so when there is issue to log in, the program needs to stop, there is nothing else to be executed. if (SuccessfulConnection == true) statement includes all the remaining codes for this program.

    Does below code act same as your suggestion?

    Code:
    OdbcConnection Cn; 
    Username = txtUsername.Text;
    Password = txtPassword.Text;
    ConnectionString = "Driver={Adaptive Server Enterprise};server=*****;port=*****;db=*****;uid=" + Username + ";pwd=" + Password + ";";
    
    
    Cn = new OdbcConnection(ConnectionString);
    //bool SuccessfulConnection = false;            
    try
    {
    Cn.Open();
    //SuccessfulConnection = true;
    }
    catch
    {
    MessageBox.Show("Invalid Username/Password.");
    return;
    }
    /
    //place form code here perhaps?
    MessageBox.Show("Login successful.");
    /

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width