dmhzx
dmhzx

Reputation: 51

How to trap errors in vb .net?

I have a load of experience with VBA and am just learning VB .net. I've written a backup utility which works fine until if finds a file that is locked. At this point it throws an exception:

System.IO.IOException: 'The process cannot access the file because another process has locked a portion of the file.

The line in question is

 FromFile.CopyTo(ToFileName, True)

With VBA I could simply trap the error and resume next. It looks like I need a "Try Catch finally" section, but have no idea how to identify this exception, and tell the program to carry on. It is a desktop application based round a form.

Upvotes: 0

Views: 779

Answers (2)

dmhzx
dmhzx

Reputation: 51

That was a great help. Thanks: Here's what I now have as a solution:

        Try
            FromFile.CopyTo(ToFileName, True)

        Catch ex As System.IO.IOException
            If ex.HResult = -2147024863 Or ex.HResult = -2147024864 Then
            Else
                MsgBox(ex.HResult & " - " & ex.Message)
            End If

        End Try

I next need to think about what to do with other exceptions, but that can wait a while.

Next step is to count the number of files looked at, and the number actually copied as a grand total across all the subfolders

Upvotes: 0

theduck
theduck

Reputation: 2617

You can just wrap your command in a Try .. Catch block:

    Try
        FromFile.CopyTo(ToFileName, True)
    Catch ex As Exception
        ' Handle the exception (if you want to)
    End Try

In this example all the details about the exception will be contained in the object ex. You don't have to have any code in the Catch section - left empty you are effectively saying ignore all errors (normally a bad thing to do).

You only need a finally section if you want to run some code all the time (whether the code in your Try worked or not):

    Try
        FromFile.CopyTo(ToFileName, True)
    Catch ex As Exception
        ' Handle the exception (if you want to)
    Finally
        ' This will execute whether there was an exception or not
    End Try

You can also catch specific exception types and handle them differently if you want to:

Try
    FromFile.CopyTo(ToFileName, True)
Catch ioEx as IO.IOException
    ' Code in this section will only be executed if an exception of type 'IO.IOException' is thrown
Catch nullEx As ArgumentNullException
    ' Handle a null argument exception
End Try

Upvotes: 2

Related Questions