Jump to content

VB.NET from beginner to advanced programmer Part 12 - Try Catch statements

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
Vswe

Vswe

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 9,552 posts
Welcome to the VB.NET tutorial series: "VB.NET from beginner to advanced programmer" which will take you from the very beginning to be a good programmer. VB.NET is a good first language for new programmers so this 21 part long series is written for completely beginners but it will also works perfectly fine if you already know another programming language.


VB.NET from beginner to advanced programmer





Right now we've come to error handling which we'll do with something called the Try Catch statement. Try Catch statements are used to catch run-time errors to prevent errors to ruin your program. The most simple type of Try Catch statements could look like this:

        Dim Number As Integer = 10
        Try
            MessageBox.Show(10 / Number)
        Catch
            MessageBox.Show("Can't divide by 0")
        End Try 

So in the above example we tries to divide 10 with a variable called number in the Try block. If an error occurs somewhere in a try block the code will immediately go to the catch block and continue from there. So if number is 0 in this case an error will occur and we will see "Can't divide by 0". Observe that the above code is not something you should really do, catching an error takes relative long time so always use if statements if it's possible, like this:

        Dim Number As Integer = 10
        If Number <> 0 Then
            MessageBox.Show(10 / Number)
        Else
            MessageBox.Show("Can't divide by 0")
        End If

But it isn't always possible to use if statements to see if an error will occur and that's what we have the try catch statements for.


We can also give a name to the exception:

        Dim myVariable As Form
        Try
            myVariable.Show()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

So now the catchblock is named ex and is of the type exception. Then we just show ex.message if an error occurs which is the error message. Which in this case will be something like "The object reference haven't been given an instance of an object.", I don't know exactly since these messages is different depending on your computer's language and mine is Swedish.


The type Exception is the standard one and will catch all exception, however we may add as many catch block we want with a different exception type. Then if an error occurs it tries to find the first catch block that matches the error which occurred. If no catch blocks matched it would be exactly the same as without any try catch statement, so a good idea is to put a general exception at the end, a little example:

        Dim myVariable As Form
        Try
            myVariable.Show()
        Catch ex As NullReferenceException
            MessageBox.Show("myVariable can't be empty")
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try





You can also specify an condition for each catch block, the condition also needs to be true for the catch block to match with the error:

        Dim Friendly As Boolean = True
        Dim myVariable As Form
        Try
            myVariable.Show()
        Catch ex As NullReferenceException When Friendly = False
            MessageBox.Show("Are you stupid? myVariable can't be empty, noob!")
        Catch ex As NullReferenceException
            MessageBox.Show("myVariable can't be empty")
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try


In the small example below the first catch block won't be run since Friendly is not equals to False. Therefor the next one will be run instead.


At the end we can add something called finally, the code in here will always be executed in the end, there's no different if an error occurred or not:


        Dim Friendly As Boolean = True
        Dim myVariable As Form
        Try
            myVariable.Show()
        Catch ex As NullReferenceException When Friendly = False
            MessageBox.Show("Are you stupid? myVariable can't be empty, noob!")
        Catch ex As NullReferenceException
            MessageBox.Show("myVariable can't be empty")
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            MessageBox.Show("We're done")
        End Try

And that was what I had to say about the Try catch statements. See you later :)

Edited by Vswe, 21 March 2010 - 02:33 PM.


#2
Guest_Jordan_*

Guest_Jordan_*
  • Guests
What if I wanted to throw my own exception, how would I do that in VB?
Nicely done, +rep!

#3
Vswe

Vswe

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 9,552 posts
This was the very last part I wrote before uploading so I completely forgot about it.

        Throw New Exception("Oh no, you did something wrong")

Edited by Vswe, 21 March 2010 - 02:33 PM.


#4
Guest_Jordan_*

Guest_Jordan_*
  • Guests
Good thing I'm here to pester you. :)

#5
Vswe

Vswe

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 9,552 posts
That's just good.

#6
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
SQL statements are a great way to generate exceptions: invalid table/field names, primary key violations, etc. +rep
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog