Solved

How can I create a custom exception class in vb.net

Posted on 2007-11-29
6
2,636 Views
Last Modified: 2012-08-14
I am using vb.net 2003 to create a custom exception handling class.  The code that I am currently using works fine but I will need to use this exception handling pages containing data connections, queries, etc. and would like to just access a custom class.   Here is a short version of the code that is working and the code snippet attached is what I have in the class so far.  The line ex.message.tostring is not working.  Any help or direction on how to accomplish this would be appreciated.  Thank-you very much.
        Try
        Catch ex As Exception
            'WORKING CODE
            'Dim file As New System.IO.StreamWriter(Server.MapPath("..\ErrorLog.txt"), True)
            'file.WriteLine(FormatDateTime(Date.Now, DateFormat.GeneralDate))
            'file.WriteLine(ex.Message.ToString())
            'file.WriteLine(ex.Source.ToString())
            'file.WriteLine(ex.StackTrace.ToString())
            'file.Close()
            'Response.Redirect("http://localhost/NetTestDocs/ErrorsRedirectPage.aspx")
            'END OF CODE
        Finally
            conn.Close()
            conn.Dispose()
        End Try
    End Sub
Public Class ErrorsClass
    Public ex As Exception
    Sub writererror()
        'Dim file As New System.IO.StreamWriter(Server.MapPath("..\ErrorLog.txt"), True)
        Dim file As New System.IO.StreamWriter(HttpContext.Current.Server.MapPath("..\ErrorLog.txt"), True)
        file.WriteLine(FormatDateTime(Date.Now, DateFormat.GeneralDate))
        'file.WriteLine(ex.Message.ToString())
        file.Close()
    End Sub
 
End Class

Open in new window

0
Comment
Question by:lnshop
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 20379240
In the catch block, re-throw your exception, but to your custom class.

An example here:
http://www.vbdotnetheaven.com/UploadFile/susanabraham/CustomExceptionHandlingvb11122005021337AM/CustomExceptionHandlingvb.aspx?ArticleID=4ce8bdfe-1a63-44da-a4a3-f8e796d63302


When you say that ex.Message.ToString() is "not working", do you mean that it's returning an empty string?

If you replace these two lines:

         'file.WriteLine(ex.Message.ToString())
         'file.WriteLine(ex.Source.ToString())

with

         'file.WriteLine(ex.ToString())

does it include the expected message? (Wishful thinking here)
0
 
LVL 44

Expert Comment

by:Arthur_Wood
ID: 20381315
you can also create your own Exception, by crearing a class the inherits from Exception:


     
Public Class MyException Inherits Exception
   Private _exceptionMessage as String
   Public ReadOnly Property ExceptionMessage() as String
      Property Get
       Return _exceptionMessage 
      End Get
   End property
   Public Sub New(ByVal Message as String)
      MyBase.New("Custom Error")
      _exceptionMessage = Message
   End Sub
 
End Class
 
 
Then you can use it like this:
 
     Try
        If someCondition then
            Throw New MyException("Something dreadful has happened")
        End if
     Catch ex as MyException
          MessageBox.Show(ex.ExceptionMessage, vbOkOnly
     Finally
     End try

Open in new window

0
 

Author Comment

by:lnshop
ID: 20385195
Thank-you so much for your help.  I have the error message working now but I am having a problem adding the error source.  Attached is the class code.  How can I add the error source to the text file.   I have tried adding source as a property and have tried adding innerException and can't get this to work. If you could help me with adding the exception source, I would appreciate it very much.

'CODE IN VB CODE BEHIND
        Catch ex As Exception
            'REFERENCE TO ERRORS CLASS
            Dim myerror As ErrorsClass
            myerror = New ErrorsClass(ex.Message)
            myerror.writererror()

'ERRORS CLASS
Imports System.Exception
Public Class ErrorsClass
    Inherits Exception
    Private _exceptionMessage As String
    Public ReadOnly Property exceptionMessage() As String
        Get
            Return _exceptionMessage
        End Get
    End Property
    Public Sub writererror()
        Dim file As New System.IO.StreamWriter(HttpContext.Current.Server.MapPath("..\ErrorLog.txt"), True)
        file.WriteLine(FormatDateTime(Date.Now, DateFormat.GeneralDate))
        file.WriteLine(Message.ToString())
        file.Close()
    End Sub
End Class

Open in new window

0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 44

Accepted Solution

by:
Arthur_Wood earned 250 total points
ID: 20386916
you need a way to create the message text.  Try this:


Imports System.Exception
Public Class ErrorsClass
    Inherits Exception
    Private _exceptionMessage As String
    Private _errorSource as String
    Public ReadOnly Property exceptionMessage() As String
        Get
            Return _exceptionMessage
        End Get
    End Property
 
    Public Sub New(byVal Message as String, byVal Source as string)
        _exceptionMessage = Message
        _errorSource = Source
    End Sub
    Public Sub writererror()
        Dim file As New System.IO.StreamWriter(HttpContext.Current.Server.MapPath("..\ErrorLog.txt"), True)
        file.WriteLine("Error occurred at: " & FormatDateTime(Date.Now, DateFormat.GeneralDate))
        file.WriteLine("Source = " & _errorSource)
        file.WriteLine("Error Message = " & _exceptionMessage)
        file.Close()
    End Sub
End Class
 
 
Then when you want to Throw the Exception:
    Try
       Code that creates the original exception
       .
       .
    Catch ex as Exception
       Throw New ErrorClass(ex.Message, "Procedure Name where the Error occurred")
    End Try
 
AW

Open in new window

0
 

Author Comment

by:lnshop
ID: 20396830
Thank-you very much.  That works great.  I have the source and stack trace being written to the error log now.
0
 
LVL 44

Expert Comment

by:Arthur_Wood
ID: 20398683
Glad to be of assistance

AW
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question