Results 1 to 21 of 21

Thread: Custom Error Handler

  1. #1

    Thread Starter
    Evil Genius alex_read's Avatar
    Join Date
    May 2000
    Location
    Espoo, Finland
    Posts
    5,538

    Custom Error Handler

    Can anyone tell me how I could get this working please??? I'm trying to create my own exception type which can be used in plase of the .Net framework one:
    Code:
    Public Class Form1 ...
    
        Private Sub Command1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles cmdGenExcep_DivideBy0.Click
            Try
                throw new System.OverflowException 
            Catch Ex as Class1
                messagebox.Show(ex.message)
            End Try
        End Sub
    
    End Class
    
    
    Public Class Class1
        Inherits Exception
    
        Public sub new(ByRef strExcepMessage As String)
            mybase.New(strExcepMessage) 
        End Sub
    End Class

    Please rate this post if it was useful for you!
    Please try to search before creating a new post,
    Please format code using [ code ][ /code ], and
    Post sample code, error details & problem details

  2. #2
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: Custom Error Handler

    First, give it a better name than Class1


    Code:
    Public Class HairyException
        Inherits System.Exception
    
    Private _mStrException As String
    
        Public sub new(ByRef strExcepMessage As String)
            _mStrException = strExcepMessage
        End Sub
    End Class
    Then to use it,

    Code:
        Private Sub Command1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles cmdGenExcep_DivideBy0.Click
            Try
                throw new HairyException("OMFG") 
            Catch Ex as HairyException
                messagebox.Show(ex.message)
            End Try
        End Sub
    
    End Class
    One thing I haven't done in the code yet is to create a message property. do this yourself, create a readonly property called message of type string, and use mStrException

  3. #3

    Thread Starter
    Evil Genius alex_read's Avatar
    Join Date
    May 2000
    Location
    Espoo, Finland
    Posts
    5,538

    Re: Custom Error Handler

    Nope, no good!

    Did you try that one out/ did this work on your machine?

    Please rate this post if it was useful for you!
    Please try to search before creating a new post,
    Please format code using [ code ][ /code ], and
    Post sample code, error details & problem details

  4. #4
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: Custom Error Handler

    Nope, haven't tried it.

  5. #5
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: Custom Error Handler

    DId you override the Message property?

  6. #6

    Thread Starter
    Evil Genius alex_read's Avatar
    Join Date
    May 2000
    Location
    Espoo, Finland
    Posts
    5,538

    Re: Custom Error Handler

    Yep!

    Please rate this post if it was useful for you!
    Please try to search before creating a new post,
    Please format code using [ code ][ /code ], and
    Post sample code, error details & problem details

  7. #7
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: Custom Error Handler

    So I finally opened up VS.NET.

    Code:
    Public Class HairyException
        Inherits System.Exception
    
        Private _msg As String
    
    
        Public Sub New(ByVal strMsg As String)
            _msg = strMsg
    
        End Sub
    
    
        Overrides ReadOnly Property Message() As String
            Get
                Return _msg
    
            End Get
        End Property
    
    End Class


    and in the form:

    Code:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Try
                Throw New HairyException("Holy cow!")
    
            Catch ex As HairyException
    
                MessageBox.Show(ex.Message)
    
            End Try
    
    
        End Sub
    Worked for me. Try copy pasting.

  8. #8

    Thread Starter
    Evil Genius alex_read's Avatar
    Join Date
    May 2000
    Location
    Espoo, Finland
    Posts
    5,538

    Re: Custom Error Handler

    Ok, sorry, to expand on that then...

    Yes this works fine, if I have a hairyexception thrown manually:

    Code:
    Public Class frmTesting_ExcepHndl 
        Inherits System.Windows.Forms.Form ...
    
        Private Sub cmdGenExcep_DivideBy0_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles cmdGenExcep_DivideBy0.Click
            Try
                throw new HairyException("ddfsdfd") 'System.OverflowException 
            Catch Ex as HairyException 
                messagebox.Show(ex.message)
            End Try
        End Sub
    End Class
    
    
    Public Class HairyException
        Inherits System.Exception
    
        Private _mStrException As String
    
        public overrides readonly property message as String
        Get        
            return _mStrException
        End Get
        End property
    
        Public sub new(ByRef strExcepMessage As String)
            _mStrException = strExcepMessage
        End Sub
    End Class
    But....

    I want to more or less replace the Exception class - whatever the exception (not just a fat, hairy one). I wanted to more-or-less create a class which deals with the exception (format it into a nice string then print it to the windows event log, that kind of thing).

    If I did another exception, say this:

    throw new System.OverflowException
    Catch Ex as HairyException

    The HairyException class won't catch that...

    Please rate this post if it was useful for you!
    Please try to search before creating a new post,
    Please format code using [ code ][ /code ], and
    Post sample code, error details & problem details

  9. #9
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: Custom Error Handler

    Since all exception classes derive from System.Exception, you could use Exception itself and work with its ex.message property.

    So in the same code, this should work:

    Code:
      Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Try
                Throw New HairyException("Holy cow!")
    
            Catch ex As Exception
    
    
                MessageBox.Show(ex.Message)
    
            End Try
    
    
        End Sub
    See what I mean?

    Now watch as I change its type to another exception thrown

    Code:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Try
                Throw New System.IO.IOException("omg lololol")
    
            Catch ex As Exception
    
                MessageBox.Show(ex.Message)
    
            End Try
    
    
        End Sub
    Still works.

    Am I understanding what you want correctly?

  10. #10

    Thread Starter
    Evil Genius alex_read's Avatar
    Join Date
    May 2000
    Location
    Espoo, Finland
    Posts
    5,538

    Re: Custom Error Handler

    I was trying to go for this kind of scenario:

    Catch Ex as HairyException
    Ex.DoSomethingWithException()
    End Try

    This bit of code (from above), works fine for a throw Hairy error, but on any other type of error, only catching Ex as a standard .Net exception works.

    Catch Ex as HairyException
    messagebox.Show(ex.message)
    End Try

    Am I making any sense here?? I want a class to act exactly as though it were the .Net Exception class, but extended / with some extra functionality/methods added to it too...

    Thanks so far btw!!

    Please rate this post if it was useful for you!
    Please try to search before creating a new post,
    Please format code using [ code ][ /code ], and
    Post sample code, error details & problem details

  11. #11
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: Custom Error Handler

    Hmm... I don't think it can be done. Can you elaborate on what features you want to add?

  12. #12

    Thread Starter
    Evil Genius alex_read's Avatar
    Join Date
    May 2000
    Location
    Espoo, Finland
    Posts
    5,538

    Talking Re: Custom Error Handler

    I just wanted to add a few routines to actually do something with the exception:

    1) A function to build the exception properties into a nice, friendly error message with all the error info in.

    2) Calls to other methods to log the error:
    a) to a file
    b) to a database
    c) to the windows event log

    Please rate this post if it was useful for you!
    Please try to search before creating a new post,
    Please format code using [ code ][ /code ], and
    Post sample code, error details & problem details

  13. #13
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: Custom Error Handler

    So what you want is an event logger. Create a class to which you can pass your error messages to, which will collect the error messages and write to a file or wherever you'd like.

    So,

    Code:
    Try
    'something
    Catch sqlx as SqlException
    EventLog.WriteEntry("An error occured.  The error is: " & sqlx.Message)
    End Try

  14. #14
    Sleep mode
    Join Date
    Aug 2002
    Location
    RUH
    Posts
    8,083

    Re: Custom Error Handler

    Example for custom exception class:
    http://www.dotnetspider.com/technolo...xceptions.aspx

  15. #15

    Thread Starter
    Evil Genius alex_read's Avatar
    Join Date
    May 2000
    Location
    Espoo, Finland
    Posts
    5,538

    Re: Custom Error Handler

    This is the kind of thing I'm after thanks (if anyone understands my dodgy attempt at a uml diagram)!!!
    Attached Files Attached Files
    Last edited by alex_read; Dec 8th, 2004 at 03:27 AM.

    Please rate this post if it was useful for you!
    Please try to search before creating a new post,
    Please format code using [ code ][ /code ], and
    Post sample code, error details & problem details

  16. #16
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: Custom Error Handler

    If I've understood your diagram correctly, I think clsExceptionThrown should call clsLogging's write event.

  17. #17

    Thread Starter
    Evil Genius alex_read's Avatar
    Join Date
    May 2000
    Location
    Espoo, Finland
    Posts
    5,538

    Re: Custom Error Handler

    I should've maybe explained that too, sorry.

    clsLogging would be a base class. Beneath it would be classes deriving this & overriding the ExecWriteEntry method - this could be a class which deals with writing to databases, a class which handles text &/or ini files, or (as in this 1st case) a class which deals with the windows event viewer making entries in that...

    The clsExceptionThrown would provide a series of the "ExecWriteEntry" methods, with different arguments each time to call this routine in these classes derived from clsLogging.

    I.e. I call:
    Code:
    Catch ex as clsException
        ex.ExecWriteEntry(intEventVwrEventId:=999)
    This would create an instance of the EventVwr class & make a call to it's ExecWriteEntry method.

    I call:
    Code:
    Catch ex as clsException
        ex.ExecWriteEntry(FileNameToWriteOut:="C:\Path\File.txt")
    This could create an instance of the TextFile class & make a call to it's ExecWriteEntry method etc.

    As a side note:
    Those 2 " ExecLogError" labels on the left there should've read "ExecWriteEntry" instead! I've updated the above attachment!
    Last edited by alex_read; Dec 8th, 2004 at 03:29 AM.

    Please rate this post if it was useful for you!
    Please try to search before creating a new post,
    Please format code using [ code ][ /code ], and
    Post sample code, error details & problem details

  18. #18
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: Custom Error Handler

    mendhak is basically correct with everything.. I see what you are trying to do, but the way the framework works, when an exception is thrown (by your code throwing one, or by the system encountering one) it will look for your catch statements and fire them in order, if you make your own exception class, you HAVE to throw it yourself. This is just how it works in .NET. The point of custom exceptions is to handle custom errors in your custom classes

    what you COULD do perhaps is set up global error handling... (I haven't tested but I imagine that any local error handling would override the global handler... but this may be something you can use (the VB.NET code is towards the bottom)

    http://dotnetjunkies.com/WebLog/mark...0/08/2152.aspx

  19. #19
    PowerPoster
    Join Date
    Jan 2004
    Location
    Southern California
    Posts
    5,034

    Re: Custom Error Handler

    Kleinma,

    Do you happen to have this C# Routine in VB.Net???
    Blake

  20. #20
    PowerPoster JuggaloBrotha's Avatar
    Join Date
    Sep 2005
    Location
    Lansing, MI; USA
    Posts
    4,286

    Re: Custom Error Handler

    the vb code is at the bottom (as kleinma pointed out):
    Here's how to get it done in VB.NET. First, create a class to intercept errors and call the ExceptionHandler.DisplayMessage() method.

    Imports System
    Imports System.ComponentModel
    Imports System.Drawing
    Imports System.Windows.Forms
    Imports System.Threading
    Imports Microsoft.VisualBasic

    'The Error Handler class
    'We need a class because event handling methods can't be static
    Friend Class CustomExceptionHandler

    'Handle the exception event
    Public Sub OnThreadException(ByVal sender As Object, ByVal t As ThreadExceptionEventArgs)
    Dim result As DialogResult = DialogResult.Cancel

    Try
    OurExceptionHandler.DisplayMessage(t.Exception)
    Catch
    Try
    MessageBox.Show("Fatal Error", "Fatal Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop)
    Finally
    Application.Exit()
    End Try
    End Try
    End Sub

    Then hook it in the Main this way:

    Public Class Main
    'The application's main entry point.
    Public Shared Sub Main()
    'Explicitly set apartment state to Single Thread Apartment (STA)
    'System.Threading.Thread.CurrentThread.ApartmentState = System.Threading.ApartmentState.STA
    Dim eh As New CustomExceptionHandler
    AddHandler Application.ThreadException, AddressOf eh.OnThreadException
    Application.Run(New ErrorHandler)
    End Sub
    End Class

    I hope some of you find this simple, yet elegant, solution as schweet as I did.
    this actually made for a good read
    Currently using VS 2015 Enterprise on Win10 Enterprise x64.

    CodeBank: All ThreadsColors ComboBoxFading & Gradient FormMoveItemListBox/MoveItemListViewMultilineListBoxMenuButtonToolStripCheckBoxStart with Windows

  21. #21
    PowerPoster
    Join Date
    Jan 2004
    Location
    Southern California
    Posts
    5,034

    Re: Custom Error Handler

    Thanks Jugga!!!
    Blake

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width