doria_aries
doria_aries

Reputation: 75

how to handle exceptions in vb.net?

I am creating a program in which a user can search and add their desired order. The problem that I'm facing now is that when I throw the exception, the program does not read the exception so that the user will know if the id that is entered is on the database or not. I will provide the code snippet of the program that I'm working on.

enter image description here

Upvotes: 0

Views: 53

Answers (2)

Shai Cohen
Shai Cohen

Reputation: 6249

Problems

  1. Your code will not throw an error if the item_code does not exist in your database. It will simply not enter the while loop.
  2. This is not the proper use of an exception. It is not an error if the record is not found. The proper way of checking if the item_code exists is a check if the datareader has results.
  3. You must properly defend yourself again SQL injection. By concatenating the sql query you are opening yourself up to a whole host of problems. For example, if a user maliciously enters the following text, it will delete the entire Products table: ';DROP TABLE Products;-
  4. You are not disposing of the OleDbConnection or the OleDbCommand objects correctly. If an exception occurs, your code will not run the Dispose() method. This can cause you to quickly run out of resources.

Solutions

  1. You should check if the dataRead has any rows. If it does not, then you can alert the user via javascript. Like so:

    If dataRead.HasRows Then
        //READ DATA
    Else
        //ALERT USER
    End If
    
  2. Solution #1 address Problem #2 as well

  3. Use a parameterized query. The .NET framework will prevent these kinds of attacks (SQL Injection).

    selectProductQuery = "SELECT * FROM Products WHERE item_code = @item_code"
    ...
    newCmd.Parameters.AddWithValue("item_code", txtItemCode.Text);
    
  4. Wrap all objects that implement Dispose() in a using block. This will guarantee everything is properly disposed of, whether an error is thrown or not.

    Using newCon As New OleDbConnection(....)
        Using newCmd As New OleDb.OleDbCommand(...)
            ...
        End Using
    End Using
    

To be perfectly honest, there is quite a bit "wrong" with your code, but this should get you headed in the right direction.

Upvotes: 1

NikolaiDante
NikolaiDante

Reputation: 18649

The line:

Response.Write(<script>alert('The ...')</script>)

Needs to be (note the quotes):

Response.Write("<script type='text/javascript'>alert('The ...')</script>")

Same for the other one at the top, but I dont think that will fix your overall problem.

Instead, use javascript like this:

if(!alert('Whoops!')){window.location.reload();}

to pop up an alert box and then reload the page after they click on the button.

Upvotes: 0

Related Questions