Question

I'm trying to download a file using this code:

Try
    My.Computer.Network.DownloadFile _
        (fileUrl, Path.Combine(mySettings.filePath, fileName), _
        "", "", False, 500, True)
Catch ex As Exception
    MsgBox(translation.GetString("msgNavError") & vbCrLf & ex.Message)
End Try

This code works and shows an error like Le nom distant n'a pas pu être résolu: '<hostname>'. It would make no sense to compare like : If ex.Message = "Le nom distant n'a pas pu être résolu: '<hostname>'" Then ..., because the message is localized.

So how could I write this pseudo-code in VB.net ?

Catch ex As Exception
    If ex.NoNetworkWorkConnection Then
        MsgBox("Your computer is not connected to the network")
    Else If ex.ServerDidntRespond Then
        MsgBox("The server did not respond")
    Else
        MsgBox("Unexpected error : " & ex.Message)
    End If
End Try

I'm using Visual Basic 2008 Express.

Was it helpful?

Solution

Use a try statement with multiple catch clauses like so

Try
'insert exception prone code here    
Throw New OutOfMemoryException
Throw New InvalidCastException

Catch ex As OutOfMemoryException
    Console.WriteLine("out of memory")

Catch ex2 As InvalidCastException
    Console.WriteLine("invalid cast")
End Try

Then if an out of memory exception is thrown the 1st catch clause will be executed if an invalid cast exception is thrown the 2nd catch clause will be executed.

You can change the exception type to whatever suits your needs as this is only an example

Hope this helps

OTHER TIPS

If you look at the help page for DownloadFile, you'll see a list of exceptions being throwned (ArgumentException, IOException, TimeoutException, SecurityException, WebException). Instead of catching a generic exception, catch the one you want.

Try
    My.Computer.Network.DownloadFile _
        (fileUrl, Path.Combine(mySettings.filePath, fileName), _
        "", "", False, 500, True)


Catch ex As ArgumentException
    MsgBox("ArgumentException")
Catch ex2 As IOException
    MsgBox("IOException")
End Try

Some exception like WebException have a property telling you which error number it is (ex Status)

You can use the TypeOf keyword...

Here's and example:

Try
    CODEZ HERE
Catch ex As Exception
    If TypeOf ex Is OutOfMemoryException Then
        MsgBox("Out of memory exception")
    End If
End Try
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top