Error handling message types - vb.net

I am using try..catch for error handling. I am getting the message displayed as
messagebox.show (ex.tostring)
But it gives very long message.
Is it possible just to get only the actual error or I could give my own modified message, based on what ex contains?
Thanks

Use Exception.Message property.
MessageBox.Show(ex.Message)

You can print the content of the Message property. Usually it's a short descriptive message without the full - technical - details of the stack.

Exception.Message contains a simple description of the exception (e.g. "Object reference not set...").
Exception.ToString() contains a description of the exception along with a complete stack trace.

The Message property returns only the message(which explains the reason for the exception).
Dim message As String = "Message: " & ex.Message
MessageBox.Show(message)
However, if you only want the name of the Exception's Type:
Dim typeName = ex.GetType().Name

If you want less text in message then try to change
Exception.ToString to Exception.Message
as Massimiliano Peluso said, and if you want to customize then I hope this will give you some idea.
Try
'Your Codes...
Catch oledbEx As OleDbException
MessageBox.Show("Your message")
Catch ex As Exception
MessageBox.Show("Your message")
Catch ioEX As IOException
MessageBox.Show("Your message")
Catch dataEX As DataException
MessageBox.Show("Your message")
End Try

Related

VB Exception ex.Message

In c++ the ex.what() function gives me the exact message I wrote when I throw the exception, but in VB when I throw an exception with a custom message and use ex.Message, I get the original message of the exception in addition to mine.
Is there a simple way to only display my custom message?
example:
Throw New ArgumentOutOfRangeException("Invalid Range")
Catch ex As ArgumentOutOfRangeException 'invalid range
MessageBox.Show(ex.Message)
End Try
Message output is:
Instead of just "Invalid Range"
If you throw an ArgumentOutOfRangeException the first parameter in the constructor is ParamName not Message. As this exception is used to indicate when an argument is out of range and ParamName to show which parameter that was.
Example:
Sub MySub(range As Integer)
Try
Throw New ArgumentOutOfRangeException(Nameof(range), "Invalid Range")
Catch ex As ArgumentOutOfRangeException
MessageBox.Show(ex.Message)
End Try
End Sub
If you just want to specify Message you need to write:
Throw New ArgumentOutOfRangeException(nothing, "Invalid Range")

i want to control the error message when calling function return an error

i want to customize my own error box and message when an error occur in calling a function .
enter image description here
i try to use try catch an exception but not doing anything
Try
L = objGeoFlowDLL.GFCalc_Main(nInputs, nOutputs, sngInputs, sngOutputs)
Catch ex As Exception
MessageBox.Show(ex.Message)
' Me.Close()
Finally
End Try
Try
L = objGeoFlowDLL.GFCalc_Main(nInputs, nOutputs, sngInputs, sngOutputs)
Catch ex As DivideByZeroException
MessageBox.Show("Custom message to be shown when something is divided by zero.")
Catch ex2 As Exception
MessageBox.Show("Custom message to be shown when any other error occurs.")
End Try

Occasional Exception Unhandled thrown although Break option is deactivated

I've set up my exceptions so that an error in the code
Try
Using Client As New WebClient
Client.DownloadFile(sExtract, sDownloadTo)
End Using
Catch ex As Exception
Debug.Print("Failed: " + sExtract)
End Try
isn't throw.
This works fine most of the time, but after like 50-100 of errors, the following exception is shown:
According to the checkbox state "Break when this exception type is thrown", which is not-activated, this exception shouldn't be shown this way, right?
What might cause this behaviour, and how could I change it so that this exception isn't thrown?
Here is an additional image of the QuickWatch:
Try
Dim Client As New WebClient
Client.DownloadFile(sExtract, sDownloadTo)
Catch ex As Exception
Console.writeline(ex.tostring)
End Try

How to Determine Exception Subtype

I'm wondering if there's a standard way to determine the sub-type of an exception. For example, for the File.Copy() method, IOException indicates that the destination file exists OR a general I/O error occurred. There are other such cases. In my exception handler, how can I determine which it is? I'm checking the end of ex.Message for the string already exists., which works, but seems awfully kludgy and unreliable.
While it is possible to check File.Exists() on the destination file, confirm overwrite with the user if it exists and then perform File.Copy() this is not atomic, which is to say, between checking and copying, it is possible for the conditions to change, for example if some other process created or copied a file into the destination location.
EDIT:
I had already changed the code based on comments here, but I just rolled it back and will post it here, just to show what I was doing:
Try
File.Copy(SrcFile, DstFile, OverWrite)
Catch ex As DirectoryNotFoundException
MsgBox(ex.Message)
Catch ex As FileNotFoundException
MsgBox("File not found: " & ex.FileName)
Catch ex As UnauthorizedAccessException
MsgBox("You do not have write access to the destination.")
Catch ex As IOException
' IOException represents an existing destination file OR a general IO error.
If SubStr(ex.Message, -15) = "already exists." Then
OverwriteCheck = MsgBox(
"Overwrite " & IO.Path.GetFileName(SrcFile) & " in destination directory?",
MsgBoxStyle.YesNo
)
If OverwriteCheck = DialogResult.Yes Then
Try
File.Copy(SrcFile, DstFile, OverWrite)
Catch iex As Exception
MsgBox("Unable to copy " & SrcFile & ":" & vbNewLine & iex.Message)
End Try
End If
Else
Throw ex
End If
Catch ex As ArgumentException
' The user left a blank line in the text box. Just skip it.
End Try
Here is an option using FileStreams to get more granular information about your exception
Sub Main()
Try
copyTo("C:\t\output3.txt", "C:\t\output1.txt", True)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.ReadLine()
End Sub
Private Sub copyTo(source As String, destination As String, Optional overwrite As Boolean = False)
' raises FileNotFoundException if source doesn't exist
Using fsSource As New FileStream(source, FileMode.Open, FileAccess.Read, FileShare.None)
If Not overwrite AndAlso File.Exists(destination) Then
' Raises exception when destination file exists and not overwrite
Throw New Exception(
String.Format("Destination file '{0}' exists and overwrite is false.", destination))
Else
Using fsDestination As New FileStream(destination, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)
fsSource.CopyTo(fsDestination)
End Using
End If
End Using
End Sub
This is a rudimentary example, but you can see how you can differentiate different exception cases, while having atomicity between checking file existence and copying.
I believe you looking for this pattern:
Try
IO.File.Copy("source", "Dest", True)
Catch exUnAuth As System.UnauthorizedAccessException
Catch exArg As System.ArgumentException
Catch exNotFound As IO.FileNotFoundException
Catch exGeneral As System.Exception
End Try
Place the list of specific exceptions first in the sequence. The last exception tested for should be the least derived.
You should read through the documentation: How to use structured exception handling in Visual Basic .NET or in Visual Basic 2005. Yes this is an old reference, but that is an indication how long this has been part of the language.

Setting a textbox property value within a catch block

Using VS 2013 VB.net for my ClickOnce application. I've got a function which verifies database functionality and the guts are wrapped in a Try Catch. A portion of my Catch block looks like this:
Catch ex As Exception When Err.Number = "5"
My.Application.Log.WriteException(ex)
If My.Settings.g_blnDebugMode Then
MessageBox.Show(Err.Number & " " & ex.ToString, "Exception Error")
End If
If Err.Description.Contains("The specified table does not exist") Then
MessageBox.Show("Selected file is not a valid database.", "Exception Error")
ElseIf Err.Description.Contains("The specified password does not match the database password.") Then
MessageBox.Show("The specified password does not match the current database password.", "Exception Error")
End If
Return False
What I want to do is, clear two different fields based on the two custom error messages at the bottom. Something like TextBox1.Text = "" or TextBox2.Text = "" depending on which error is thrown (invalid password or invalid database). My problem is that I don't seem to be able to set them directly or set the value of a module or global variable from within the catch block.
Error is:
Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.
If it's possible how can I work around this and set my TextBoxes based on the results in the Catch block?
Usually the method to achieve what you are trying is to use a second a catch block
Catch ex As Exception When Err.Number = ""
MessageBox.Show(ex.Message)
FlushTextBox1();
Catch ex As Exception When Err.Number = ""
MessageBox.Show(ex.Message)
FlushTextBox2();
The error is likely appearing because the try-catch block is inside a Shared method. What that means is, the change in the value of TextBox will be repeated for all instances of the class. If you want the TextBox to behave like this, add the Shared keyword to its own declaration and remove it from the Sub's declaration. If you don't want this behaviour at all, just remove the Shared keyword. For more information on the error check the MSDN article
Alternatively you can call a local function (as shown in code) FlushTextBox1() to change the value of the TextBox outside the Sub.