NeuralJack
Centurion
- Joined
- Jul 28, 2005
- Messages
- 138
I have been told a few times that the best thing to do when programming is to try to avoid raising any and all potential errors, instead of using the raised errors themselves to figure out what to do next. At least, this is what I took from it.
So, I'm wondering if you guys think this should be done during simple math calculations too.. in order to avoid things like overflow? Do you check each and every math operation you do before you do it, or do you let the try/catch handle an error the way you want it?
Simple Case:
You want to add 2 user entered Integers together. If there is an overflow set the Total to Maximum Int 64 Value.
Addition Method 1 (Use Try/Catch)
Addition Method 2 (Check for overflow yourself before addition, to avoid raising errors)
I don't know, Method 2 just seems a little excessive to me. But you guys have slapped me straight many times and I'm beggin for more. Let me know what you think.
So, I'm wondering if you guys think this should be done during simple math calculations too.. in order to avoid things like overflow? Do you check each and every math operation you do before you do it, or do you let the try/catch handle an error the way you want it?
Simple Case:
You want to add 2 user entered Integers together. If there is an overflow set the Total to Maximum Int 64 Value.
Addition Method 1 (Use Try/Catch)
Code:
Dim Int1 As Int64 = 'User enters a value
Dim Int2 As Int64 = 'User enters a value
Dim Total As Int64
Try
Total = Int1 + Int2
Catch ex1 as System.OverflowException
Total = Int64.MaxValue
End Try
Addition Method 2 (Check for overflow yourself before addition, to avoid raising errors)
Code:
Private Sub AddThis()
Dim Int1 As Int64 = 'User enters a value
Dim Int2 As Int64 = 'User enters a value
Dim Total As Int64
If AdditionIsOK()
Total = Int1 + Int2
Else
Total = int64.MaxValue
End If
End Sub
Private Function AdditionIsOK(ByVal Int1 as int64,ByVal Int2 as int64) as boolean
If Int1 >= 0 And Int2 >= 0 Then 'Both Numbers are Positive
Dim MaxAllowedInt2 as int64 = Int64.MaxValue - Int1
If Int2 <= MaxAllowedInt2
Return True
EndIf
ElseIf ... 'Code for when Both Numbers are Negative
ElseIf ... 'Code for when Int1 is Negative and Int2 is Positive
ElseIf ... 'Code for when Int2 is Negative and Int1 is Positive
EndIf
Return False
End Function
I don't know, Method 2 just seems a little excessive to me. But you guys have slapped me straight many times and I'm beggin for more. Let me know what you think.