Evaluating Multiple Expressions in an If Statement

Published on January 8, 2010

It is common to have multiple expressions in an If statement using logical operators And, Or, etc. Remember that every expression in the If statement will always be evaluated, even if a previous expression renders the entire statement False. This could cause an unexpected error in certain situations.

' 
' Even if x=0 the second expression will be evaluated 
' raising a divide by 0 error.
' 
If (x > 0) And (y / x > 1) Then
        ' Do something here
    End If

' 
' Separate the expressions to avoid a divide by 0 error. 
' 
    If (x > 0) Then
        If (y / x > 1) Then
            ' Do something here
        End If
    End If

Tags:
Like this article? Share it!

Leave a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Privacy Policy