-
November 19th, 2012, 09:22 AM
#1
exception errors
I am beginning to use exceptions in visual basic and haveing issues with my compute button(totals button works fine). My issue is I have a group box of customer information and the customer name, shipping address, and telephone cannot be blank and just need help on how I can throw exception with this. I also have a purchase information group box that checks to make sure product identifier, purchase price, and quantity purchased are not blank either. I was able to get this to work fine for purchase price and quantity purchased but does not work for product identifier. If someone could please walk me through this so I hopefully wont have to ask how to do exceptions again. Here is my code and if I need to explain anything better please let me know...
Code:
Public Class Form1
'Declare module level variables
Private totalDiscountDecimal As Decimal
Private totalQuantityInteger As Integer
Private Sub computeButton_Click(sender As Object, e As EventArgs) Handles computeButton.Click
'Begin try statement to check for errors
Try
'Declare constant for sales tax
Const SALES_TAX As Single = 0.05
Const FED_EX_AIR As Single = 25.0
Const FED_EX_GROUND As Single = 20.0
Const US_POSTAL As Single = 12.0
Const ONE_YEAR_WARRANTY As Single = 75.0
Const CLUB_MEMBERSHIP As Single = 150.0
Const TIRE_SALE As Single = 25.0
Const WHOLESALE_DISCOUNT As Single = 0.1
Const RETAIL_DISCOUNT As Single = 0.0
'Declare variables
Dim subtotalDecimal, totalDueDecimal, salesTaxDecimal, shippingCostDecimal, oneYearWarrantyDecimal,
extrasDecimal, clubMembershipDecimal, tireSaleDecimal, discountDecimal As Decimal
'Declare variables and convert values from textbox controls to memory
Dim purchasePriceDecimal As Decimal = Decimal.Parse(purchasePriceTextBox.Text, Globalization.NumberStyles.Currency)
Dim quantityPurchasedInteger As Integer = Integer.Parse(quantityPurchasedTextBox.Text, Globalization.NumberStyles.Number)
'Determine the shipping cost if fed ex air is clicked
If fedExAirRadioButton.Enabled Then
shippingCostDecimal = FED_EX_AIR
ElseIf fedExGroundRadioButton.Enabled Then
shippingCostDecimal = FED_EX_GROUND
ElseIf USPostalRadioButton.Enabled Then
shippingCostDecimal = US_POSTAL
End If
'Calculate total shipping cost
shippingCostDecimal *= quantityPurchasedInteger
'Show the results in a textbox
shippingCostTextBox.Text = shippingCostDecimal
'Check extras
If oneYearWarrantyCheckBox.Checked Then
oneYearWarrantyDecimal = ONE_YEAR_WARRANTY
End If
If clubMembershipCheckBox.Checked Then
clubMembershipDecimal = CLUB_MEMBERSHIP
End If
If tireSaleCheckBox.Checked Then
tireSaleDecimal = TIRE_SALE
End If
'Determine extrasDecimal
extrasDecimal = oneYearWarrantyDecimal + clubMembershipDecimal + tireSaleDecimal
'Determine the discount
If wholesaleRadioButton.Checked Then
discountDecimal = (purchasePriceDecimal * quantityPurchasedInteger) * WHOLESALE_DISCOUNT
ElseIf retailRadioButton.Checked Then
discountDecimal = RETAIL_DISCOUNT
End If
subtotalDecimal = purchasePriceDecimal * quantityPurchasedInteger + shippingCostDecimal + extrasDecimal - discountDecimal
'Determine the sales tax
If wholesaleRadioButton.Checked Then
salesTaxDecimal = 0.0
ElseIf retailRadioButton.Checked Then
salesTaxDecimal = subtotalDecimal * SALES_TAX
End If
'Determine the total due
totalDueDecimal = subtotalDecimal + salesTaxDecimal
'Display output in textboxes
salesTaxTextBox.Text = salesTaxDecimal.ToString("C")
subtotalTextBox.Text = subtotalDecimal.ToString("C")
shippingCostTextBox.Text = shippingCostDecimal.ToString("C")
costOfExtrasTextBox.Text = extrasDecimal.ToString("C")
discountTextBox.Text = discountDecimal.ToString("C")
totalDueTextBox.Text = totalDueDecimal.ToString("C")
'Enable\Disable buttons
computeButton.Enabled = False
resetButton.Enabled = True
'Accumulate totals
totalDiscountDecimal += discountDecimal
totalQuantityInteger += quantityPurchasedInteger
Catch ex As Exception
MessageBox.Show("Product identifier, purchase price, or quantity purchased has not been entered!",
"Customer name error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub totalCountAverageButton_Click(sender As Object, e As EventArgs) Handles totalCountAverageButton.Click
'Try statement to check for errors
Try
'Determine the average Discount
Dim averageDiscountDecimal = totalDiscountDecimal / totalQuantityInteger
'Display totals in a message string
Dim messageString As String = "Total Wholesale Discounts: " & totalDiscountDecimal.ToString("C") &
ControlChars.NewLine & "Total Wholesale Quantity Sold: " & totalQuantityInteger.ToString("N0") &
ControlChars.NewLine & "Average Discount Amount: " & averageDiscountDecimal.ToString("C")
'Display a header for the message string
MessageBox.Show(messageString, "Totals, Counts and Averages", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch exArithmeticException As ArithmeticException
MessageBox.Show("No products have been sold yet", "Zero Sales Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show("Unexpected error - inform the system administrator", "Unknown error in totals",
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub resetButton_Click(sender As Object, e As EventArgs) Handles resetButton.Click
'Clear the textboxes
customerNameTextBox.Clear()
shippingAddressTextBox.Clear()
telephoneMaskedTextBox.Clear()
productIdentifierTextBox.Clear()
purchasePriceTextBox.Clear()
quantityPurchasedTextBox.Clear()
shippingCostTextBox.Clear()
costOfExtrasTextBox.Clear()
discountTextBox.Clear()
subtotalTextBox.Clear()
salesTaxTextBox.Clear()
totalDueTextBox.Clear()
'Set radio buttons back to default
wholesaleRadioButton.Checked = True
fedExAirRadioButton.Checked = True
'Uncheck all the extras checkboxes
oneYearWarrantyCheckBox.Checked = False
clubMembershipCheckBox.Checked = False
tireSaleCheckBox.Checked = False
'Set the focus to the customer name textbox
customerNameTextBox.Focus()
'Enable\disable buttons
computeButton.Enabled = True
resetButton.Enabled = False
End Sub
Private Sub exitButton_Click(sender As Object, e As EventArgs) Handles exitButton.Click
'Exit the program with being prompted to exit
Dim response As Integer
response = MessageBox.Show("Do you want to close the form?", "Quit?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
If response = vbYes Then
Me.Close()
End If
End Sub
End Class
-
November 19th, 2012, 01:39 PM
#2
Re: exception errors
You don't need to use EXCEPTION HANDLING for that. That is more for system errors, not program errors. Just check if the field(s) are BLANK or NOTHING, and set a flag for each one. Set it FALSE before the checks, and if there is ANY error, each one can set it to TRUE. Check for TRUE before executing the code which might cause the exception. Of course, if there is any chance of a missing CD or Network Share, then, use and EXCEPTION. ON ERROR XXX
Here's a quick sample:
Code:
Public Function DigestFileToHS(InFile As String) As String
On Error GoTo errorhandler
GoSub begin
errorhandler:
DigestFileToHexStr = ""
Exit Function
begin:
Dim FileO As Integer
FileO = FreeFile
Call FileLen(InFile)
Open InFile For Binary Access Read As #FileO
MD5Init
Do While Not EOF(FileO)
Get #FileO, , ByteBuffer
If Loc(FileO) < LOF(FileO) Then
ByteCounter = ByteCounter + 64
MD5Transform ByteBuffer
End If
Loop
ByteCounter = ByteCounter + (LOF(FileO) Mod 64)
Close #FileO
MD5Final
DigestFileToHS = GetValues
End Function
-
November 19th, 2012, 02:13 PM
#3
Re: exception errors
I am only in chapter 4 on this visual basic book so the code below is way over my head as this stage lol.
I kind of messed around with it alittle and I do get an error to come up now with the code below but the only issue is aftern the error does come up the program still computer the totals...
Code:
Public Class Form1
'Declare module level variables
Private totalDiscountDecimal As Decimal
Private totalQuantityInteger As Integer
Private Sub computeButton_Click(sender As Object, e As EventArgs) Handles computeButton.Click
'Begin try statement to check for errors
Try
'Declare constant for sales tax
Const SALES_TAX As Single = 0.05
Const FED_EX_AIR As Single = 25.0
Const FED_EX_GROUND As Single = 20.0
Const US_POSTAL As Single = 12.0
Const ONE_YEAR_WARRANTY As Single = 75.0
Const CLUB_MEMBERSHIP As Single = 150.0
Const TIRE_SALE As Single = 25.0
Const WHOLESALE_DISCOUNT As Single = 0.1
Const RETAIL_DISCOUNT As Single = 0.0
'Declare variables
Dim subtotalDecimal, totalDueDecimal, salesTaxDecimal, shippingCostDecimal, oneYearWarrantyDecimal,
extrasDecimal, clubMembershipDecimal, tireSaleDecimal, discountDecimal As Decimal
'Declare variables and convert values from textbox controls to memory
Dim purchasePriceDecimal As Decimal = Decimal.Parse(purchasePriceTextBox.Text, Globalization.NumberStyles.Currency)
Dim quantityPurchasedInteger As Integer = Integer.Parse(quantityPurchasedTextBox.Text, Globalization.NumberStyles.Number)
If customerNameTextBox.Text = String.Empty Then
MessageBox.Show("Customer name cannot be blank", "Customer name error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
customerNameTextBox.Focus()
End If
If shippingAddressTextBox.Text = String.Empty Then
MessageBox.Show("Shipping address cannot be blank", "Shipping address error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
customerNameTextBox.Focus()
End If
If telephoneMaskedTextBox.Text = String.Empty Then
MessageBox.Show("Phone number cannot be blank", "Telephone error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
customerNameTextBox.Focus()
End If
'Determine the shipping cost if fed ex air is clicked
If fedExAirRadioButton.Enabled Then
shippingCostDecimal = FED_EX_AIR
ElseIf fedExGroundRadioButton.Enabled Then
shippingCostDecimal = FED_EX_GROUND
ElseIf USPostalRadioButton.Enabled Then
shippingCostDecimal = US_POSTAL
End If
'Calculate total shipping cost
shippingCostDecimal *= quantityPurchasedInteger
'Show the results in a textbox
shippingCostTextBox.Text = shippingCostDecimal
'Check extras
If oneYearWarrantyCheckBox.Checked Then
oneYearWarrantyDecimal = ONE_YEAR_WARRANTY
End If
If clubMembershipCheckBox.Checked Then
clubMembershipDecimal = CLUB_MEMBERSHIP
End If
If tireSaleCheckBox.Checked Then
tireSaleDecimal = TIRE_SALE
End If
'Determine extrasDecimal
extrasDecimal = oneYearWarrantyDecimal + clubMembershipDecimal + tireSaleDecimal
'Determine the discount
If wholesaleRadioButton.Checked Then
discountDecimal = (purchasePriceDecimal * quantityPurchasedInteger) * WHOLESALE_DISCOUNT
ElseIf retailRadioButton.Checked Then
discountDecimal = RETAIL_DISCOUNT
End If
subtotalDecimal = purchasePriceDecimal * quantityPurchasedInteger + shippingCostDecimal + extrasDecimal - discountDecimal
'Determine the sales tax
If wholesaleRadioButton.Checked Then
salesTaxDecimal = 0.0
ElseIf retailRadioButton.Checked Then
salesTaxDecimal = subtotalDecimal * SALES_TAX
End If
'Determine the total due
totalDueDecimal = subtotalDecimal + salesTaxDecimal
'Display output in textboxes
salesTaxTextBox.Text = salesTaxDecimal.ToString("C")
subtotalTextBox.Text = subtotalDecimal.ToString("C")
shippingCostTextBox.Text = shippingCostDecimal.ToString("C")
costOfExtrasTextBox.Text = extrasDecimal.ToString("C")
discountTextBox.Text = discountDecimal.ToString("C")
totalDueTextBox.Text = totalDueDecimal.ToString("C")
'Enable\Disable buttons
computeButton.Enabled = False
resetButton.Enabled = True
'Accumulate totals
totalDiscountDecimal += discountDecimal
totalQuantityInteger += quantityPurchasedInteger
Catch ex As Exception
MessageBox.Show("Product identifier, purchase price, or quantity purchased has not been entered!",
"Customer name error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub totalCountAverageButton_Click(sender As Object, e As EventArgs) Handles totalCountAverageButton.Click
'Try statement to check for errors
Try
'Determine the average Discount
Dim averageDiscountDecimal = totalDiscountDecimal / totalQuantityInteger
'Display totals in a message string
Dim messageString As String = "Total Wholesale Discounts: " & totalDiscountDecimal.ToString("C") &
ControlChars.NewLine & "Total Wholesale Quantity Sold: " & totalQuantityInteger.ToString("N0") &
ControlChars.NewLine & "Average Discount Amount: " & averageDiscountDecimal.ToString("C")
'Display a header for the message string
MessageBox.Show(messageString, "Totals, Counts and Averages", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch exArithmeticException As ArithmeticException
MessageBox.Show("No products have been sold yet", "Zero Sales Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show("Unexpected error - inform the system administrator", "Unknown error in totals",
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub resetButton_Click(sender As Object, e As EventArgs) Handles resetButton.Click
'Clear the textboxes
customerNameTextBox.Clear()
shippingAddressTextBox.Clear()
telephoneMaskedTextBox.Clear()
productIdentifierTextBox.Clear()
purchasePriceTextBox.Clear()
quantityPurchasedTextBox.Clear()
shippingCostTextBox.Clear()
costOfExtrasTextBox.Clear()
discountTextBox.Clear()
subtotalTextBox.Clear()
salesTaxTextBox.Clear()
totalDueTextBox.Clear()
'Set radio buttons back to default
wholesaleRadioButton.Checked = True
fedExAirRadioButton.Checked = True
'Uncheck all the extras checkboxes
oneYearWarrantyCheckBox.Checked = False
clubMembershipCheckBox.Checked = False
tireSaleCheckBox.Checked = False
'Set the focus to the customer name textbox
customerNameTextBox.Focus()
'Enable\disable buttons
computeButton.Enabled = True
resetButton.Enabled = False
End Sub
Private Sub exitButton_Click(sender As Object, e As EventArgs) Handles exitButton.Click
'Exit the program with being prompted to exit
Dim response As Integer
response = MessageBox.Show("Do you want to close the form?", "Quit?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
If response = vbYes Then
Me.Close()
End If
End Sub
End Class
-
November 19th, 2012, 11:37 PM
#4
Re: exception errors
Print out the values as the error occurs.
Code:
Catch ex As Exception
MessageBox.Show("Product identifier, purchase price, or quantity purchased has not been entered!",
' Debug.Print x & vbCrLf & y & vbCrLf & z
It should help identify the error. You can use an ON ERROR statement, with the TRY/CATCH
-
November 20th, 2012, 12:05 PM
#5
Re: exception errors
Doesn't look quite like classic VB6 to me. is this .net you're working with by any chance?
Please remember to rate the posts and threads that you find useful.
How can something be both new and improved at the same time?
-
November 20th, 2012, 12:31 PM
#6
Re: exception errors
I used your advice and added a messagebox to check each textbox and worked great with the exception of the masked textbox. I am guessing since there are '(', ')', and '-' already in the textbox that I will need to use a different way of checking to make sure all 10 digits are entered. All i found was the following code which did not work
If telephoneTextbox.Text = nothing then
Here is the code which I have shortened up....
Code:
'Declare Dim statements to check for errors
Dim customerNameError As New System.Text.StringBuilder
Dim shippingAddressNameError As New System.Text.StringBuilder
Dim telephoneError As New System.Text.StringBuilder
Dim productIdentifierError As New System.Text.StringBuilder
'If statement to check if customer name is blank
If String.IsNullOrWhiteSpace(customerNameTextBox.Text) Then
customerNameError.AppendLine("Name required")
customerNameTextBox.Focus()
End If
'Message box for error in customer name
If customerNameError.ToString.Length > 0 Then
MessageBox.Show(customerNameError.ToString, "Error in Customer Information", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
'If statement to check if shipping address is blank
If String.IsNullOrWhiteSpace(shippingAddressTextBox.Text) Then
shippingAddressNameError.AppendLine("Shipping address required")
shippingAddressTextBox.Focus()
End If
'Message box for error in shipping address
If shippingAddressNameError.ToString.Length > 0 Then
MessageBox.Show(shippingAddressNameError.ToString, "Error in Shipping Information", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
'If statement to check if telephone number is valid
If String.IsNullOrWhiteSpace(telephoneMaskedTextBox.Text) Then
telephoneError.AppendLine("Telephone required")
End If
'Message box for error in telephone number
If telephoneError.ToString.Length < 0 Then
MessageBox.Show(customerNameError.ToString, "Error in Telephone Number", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
'If statement to check if product identifier is blank
If String.IsNullOrWhiteSpace(productIdentifierTextBox.Text) Then
productIdentifierError.AppendLine("Product Identifier required")
productIdentifierTextBox.Focus()
End If
'Messagebox for error in product identifier
If productIdentifierError.ToString.Length < 0 Then
MessageBox.Show(productIdentifierError.ToString, "Errors in Purchase Information", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
-
November 20th, 2012, 01:09 PM
#7
Re: exception errors
Use a HIDDEN textbox for the MASKED TB. Let user type into normal textbox, check it, and then show the MTB with the value
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|