Prova a dare un' occhiata anche qui:
http://www.pierotofy.it/pages/guide/Guida_al_Visual_Basic_dotNET/Gestione_degli_errori/
http://www.pierotofy.it/pages/guide_tutorials/Visual_Basic/Scegliere_il_tipo_di_eccezione_pi_adatta/
Di seguito un esempio, è una form con una textbox e un button dove si genera un eccezione assegnando il valore della textbox alla variabile di tipo byte.
Le eccezioni specifiche che vengono intercettate sono due:
OverflowException se nella textbox viene inserito un numero maggiore di 255
InvalidCastException se nella textbox viene inserito un "non numero"...
Il terzo Catch intercetta tutte le altre.
NB: Il blocco Finally viene eseguito SEMPRE a prescindere che ci sia o meno un' eccezione. Le variabili dichiarate all' interno dei singoli blocchi non sono visibili all' esterno.
Public Class Form1
Dim a As Byte
Private Sub Button1_Click() Handles Button1.Click
Dim errore As Boolean = False
Dim tipo As Integer
Dim errorMsg As String
Dim log As String
Try
a = TextBox1.Text
Catch ovrEX As System.OverflowException
errore = True
log = ovrEX.ToString
errorMsg = ovrEX.Message
tipo = 1
Catch castEX As System.InvalidCastException
errore = True
log = castEX.ToString
errorMsg = castEX.Message
tipo = 2
Catch genEX As Exception
errore = True
log = genEX.ToString
errorMsg = genEX.Message
tipo = 3
Finally
If errore = True Then
'questa varabile non è visibile all' esterno
Dim msg As String
If tipo = 1 Then
msg = "Inserire numeri da 0 a 255"
End If
If tipo = 2 Then
msg = "Lettere non ammesse"
End If
If tipo = 3 Then
msg = "Errore non previsto"
End If
MsgBox(msg & vbCrLf & vbCrLf & _
"errore: " & vbCrLf & errorMsg & _
vbCrLf & vbCrLf & _
"errore completo: " & vbCrLf & log)
Else
MsgBox("OK!")
End If
End Try
End Sub
End Class
Ciao!