VB.net exception class

RCMiller1981
RCMiller1981 used Ask the Experts™
on
I am trying to use the exception class as coded below to create a new exception with a specific error number, I thought reading the descriptor of HRESULT that I would be able to set the value using a '=', however it throws an error when I do this.  My next step was to implement a partial class that overloads the property for HRESULT, however I obviously either did that wrong, or am trying to use the partial class in a way that it is not meant to.  So, How can I Set a custom Exception, with a custom error number in VB.net?

Dim ex As New Exception("Error message!")
ex.HResult = Int(10001981)
errors()

Open in new window


Partial Class

Partial Class exception
    Inherits System.Exception
    Dim hresult_holder
    Public Overloads Property HRESULT As Integer
        Get
            Return hresult_holder
        End Get
        Set(value As Integer)
            hresult_holder = value
        End Set
    End Property
End Class

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2015
Commented:
You cannot create a Partial class from a class that is already compiled. Partial is used to combine source code from 2 files when you are compiling. It works only if you have the source code.

HResult are usually reserved for system errors. Along with the error code, they also provide information about the severity of the problem and where it comes from.

What you need to do is to create your own exception class by inheriting from Exception, and add your own property to it.
Public Class MyException
	Inherits System.Exception

	Private _ErrorCode As Integer

	Friend Sub New(errorCode As Integer)
		_ErrorCode = errorCode
	End Sub

	Public ReadOnly Property ErrorCode As Integer
		Get
			Return _ErrorCode
		End Get
	End Property

End Class

Open in new window

When you need to trigger that exception, simply use code like the following:
Throw New MyException(12345)

Open in new window

Author

Commented:
That is what I feared, This solution was my backup, and now my primary....

Thank you

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial