Home > Articles

  • Print
  • + Share This
This chapter is from the book

Custom Exceptions

Implement error handling in the UI: Create and implement custom error messages.

Implement error handling in the UI: Create and implement custom error handlers.

TIP

Use ApplicationException As Base Class for Custom Exceptions Although you can derive directly from the Exception class, Microsoft recommends that you derive any custom exception class you create for your Windows application from the ApplicationException class.

In most cases, .NET's built-in exception classes, combined with custom messages that you create when instantiating a new exception, will suffice your exception handling requirements. However, in some cases you need exception types specific to the problem you are solving.

The .NET Framework allows you to define custom exception classes. To make your custom Exception class work well with the .NET exception handling framework, Microsoft recommends that you consider the following when you're designing a custom exception class:

  • Create an exception class only if no existing exception class satisfies your requirement.

  • Derive all programmer-defined exception classes from the System.ApplicationException class.

  • End the name of custom exception class with the word Exception (for example, MyOwnCustomException).

  • Implement three constructors with the signatures shown in the following code:

    Public Class MyOwnCustomException
      Inherits ApplicationException
    
      ' Default constructor
      Public Sub New()
    
      End Sub
    
      ' Constructor accepting a single string message
      Public Sub New(ByVal message As String)
        MyBase.New(message)
      End Sub
    
      ' Constructor accepting a string message 
      ' and an inner exception 
      ' that will be wrapped by this custom exception class
      Public Sub New(ByVal message As String, _
       ByVal inner As Exception)
        MyBase.new(message, inner)
      End Sub
    
    End Class

Step By Step 3.4 shows how to create a custom exception.

STEP BY STEP 3.4 Creating a Custom Exception

  1. Add a new Windows Form to your Visual Basic .NET project.

  2. Place two Label controls, a TextBox control named txtDate, and a Button control named btnIsLeap on the form. Figure 3.6 shows a design for this form. Name the empty Label control lblResults.

Figure 3.6 Leap Year Finder.

  1. Add a new class to your project. Add code to create a custom exception class:

    Public Class MyOwnInvalidDateFormatException
      Inherits ApplicationException
    
      ' Default constructor
      Public Sub New()
    
      End Sub
    
      ' Constructor accepting a single string message
      Public Sub New(ByVal message As String)
        MyBase.New(message)
        Me.HelpLink = _
         "file://MyOwnInvalidDateFormatExceptionHelp.htm"
      End Sub
    
      ' Constructor accepting a string 
      ' message and an inner exception 
      ' that will be wrapped by this custom exception class
      Public Sub New(ByVal message As String, _
       ByVal inner As Exception)
        MyBase.new(message, inner)
        Me.HelpLink = _
         "file://MyOwnInvalidDateFormatExceptionHelp.htm"
      End Sub
    

    End Class

  2. Add a second new class to your project. Add code to create a class named LeapDate:

    Public Class LeapDate
      ' This class does elementary date handling for the
      ' leap year form
      Private day, month, year As Integer
    
      Public Sub New(ByVal strDate As String)
        If strDate.Trim().Length = 10 Then
          ' Input data might be in invalid 
          ' format; in that case
          ' the Convert.ToDateTime method will fail
          Try
            Dim dt As DateTime = _
             Convert.ToDateTime(strDate)
            day = dt.Day
            month = dt.Month
            year = dt.Year
            ' Catch any exception, attach 
            ' it to the custom exception and
            ' throw the custom exception
          Catch e As Exception
            Throw New MyOwnInvalidDateFormatException( _
             "Custom Exception: Invalid Date Format", e)
          End Try
        Else
          ' bad input, throw a custom exception
          Throw New MyOwnInvalidDateFormatException( _
           "The input does not match the required " & _
           "format: MM/DD/YYYY")
        End If
      End Sub
    
      ' Find if the given date belongs to a leap year
      Public Function IsLeapYear() As Boolean
        IsLeapYear = (year Mod 4 = 0) And _
         ((year Mod 100 <> 0) Or (year Mod 400 = 0))
      End Function
    End Class
  3. Add the following event handler for the Click event of btnIsLeap:

    Private Sub btnIsLeap_Click(ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles btnIsLeap.Click
      Try
        Dim dt As LeapDate = New LeapDate(txtDate.Text)
        If dt.IsLeapYear() Then
          lblResult.Text = "This date is in a leap year"
        Else
          lblResult.Text = _
           "This date is NOT in a leap year"
        End If
        ' Catch the custom exception and 
        ' display an appropriate message
      Catch dte As MyOwnInvalidDateFormatException
        Dim msg As String
        ' If some other exception was also 
        ' attached with this exception
        If Not dte.InnerException Is Nothing Then
          msg = String.Format( _
           "Message:" & vbCrLf & "{0}" & _
           vbCrLf & vbCrLf & "Inner Exception:" & _
           vbCrLf & "{1}", _
           dte.Message, dte.InnerException.Message)
        Else
          msg = String.Format("Message:" & _
           vbCrLf & "{0}" & _
           vbCrLf & vbCrLf & _
           "Help Link:" & vbCrLf & "{1}", _
           dte.Message, dte.HelpLink)
        End If
        MessageBox.Show(msg, dte.GetType().ToString())
      End Try
    End Sub
  4. Set the form as the startup object for the project.

  5. Run the project. Enter a date and click the button. If the date was in the correct format, you'll see a result displayed in the Results label. Otherwise, you'll get a message box showing the custom error message thrown by the custom exception, as shown in Figure 3.7.

Figure 3.7 Custom error message thrown by the custom exception.

In Guided Practice Exercise 3.1 you'll create a custom defined Exception class that helps implement custom error messages and custom error handling in your programs.

GUIDED PRACTICE EXERCISE 3.1

Your goal is to create a keyword-searching application. The application should ask for a filename and a keyword and search for the keyword in the file. The application should then display the number of lines that contain the keyword. The application assumes that the entered keyword will be a single word. If not, you must create and throw a custom exception for that case.

Try this on your own first. If you get stuck or would like to see one possible solution, follow these steps:

  1. Add a new form to your Visual Basic .NET Project.

  2. Place three Label controls, two TextBox controls, and two Button controls on the form, arranged as shown in Figure 3.8. Name the TextBox for accepting filenames txtFileName and the Browse button btnBrowse. Name the TextBox for accepting keywords txtKeyword and the search button btnSearch. Name the results label lblResult.

Figure 3.8 Form allowing a keyword search in a file.

  1. Add an OpenFileDialog control to the form and change its name to dlgOpenFile.

  2. Create a new class named BadKeywordFormatException that derives from ApplicationException and place the following code in it:

    Public Class BadKeywordFormatException
      Inherits ApplicationException
    
      ' Default constructor
      Public Sub New()
    
      End Sub
    
      ' Constructor accepting a single string message
      Public Sub New(ByVal message As String)
        MyBase.New(message)
      End Sub
    
      ' Constructor accepting a string 
      ' message and an inner exception 
      ' that will be wrapped by this custom exception class
      Public Sub New(ByVal message As String, _
       ByVal inner As Exception)
        MyBase.new(message, inner)
      End Sub
    
    End Class
  3. Create a method named GetKeywordFrequency in the form's module. This class accepts a filename and returns the number of lines containing the keyword. Add the following code to the method:

    Private Function GetKeywordFrequency( _
     ByVal strPath As String) As Integer
      If Me.txtKeyword.Text.Trim().IndexOf(" ") >= 0 Then
        Throw New BadKeywordFormatException( _
         "The keyword must only have a single word")
      End If
    
      Dim count As Integer = 0
      If File.Exists(strPath) Then
        Dim sr As StreamReader = _
         New StreamReader(txtFileName.Text)
        Do While (sr.Peek() > -1)
          If sr.ReadLine().IndexOf(txtKeyword. _
           Text) >= 0 Then
            count += 1
          End If
        Loop
      End If
      GetKeywordFrequency = count
    End Function
  4. Add the following code to the Click event handler of the btnBrowse button:

    Private Sub btnBrowse_Click(ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles btnBrowse.Click
      If dlgOpenFile.ShowDialog() = DialogResult.OK Then
        txtFileName.Text = dlgOpenFile.FileName
      End If
    End Sub
  5. Add the following code to the Click event handler of the btnSearch Button:

    Private Sub btnSearch_Click(ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles btnSearch.Click
      If txtKeyword.Text.Trim().Length = 0 Then
        MessageBox.Show( _
         "Please enter a keyword to search", _
         "Missing Keyword")
        Exit Sub
      End If
      Try
      lblResult.Text = String.Format("The keyword: '{0}'" & _
       "was found in {1} lines", _
         txtKeyword.Text, _
         GetKeywordFrequency(txtFileName.Text))
      Catch bkfe As BadKeywordFormatException
        Dim msg As String = _
         String.Format("Message:" & vbCrLf & _
         "{0}" & vbCrLf & vbCrLf & "StackTrace:" & _
         vbCrLf & "{1}", _
         bkfe.Message, bkfe.StackTrace)
        MessageBox.Show(msg, bkfe.GetType().ToString())
      End Try
    End Sub
  6. Set the form as the startup object for the project.

  7. Run the project. Click the Browse button and select an existing file. Enter a keyword to search for in the file and press the Search button. If the keyword entered is in wrong format (contains a space) then the custom exception will be raised.

  • + Share This
  • 🔖 Save To Your Account