Lab 5-2: Creating, Throwing, and Handling Exceptions
In this lab, you will create a custom exception that represents an attempt to divide by zero. Since you will raise this exception from the application, you will use a custom exception rather than the built-in DivideByZeroException. You will create code to test whether division by zero is taking place, and throw the exception when division by zero takes place. Finally, you will add code to handle the exception and allow the application to continue gracefully. The solution to this lab is available on the Supplemental Course Materials CD-ROM in the \Labs\Ch05\Lab 5-2\Solution folder.
Before You Begin
You should have completed Lab 5-1 or loaded the Lab 5-1 solution from the Supplemental Course Materials CD-ROM.
Estimated lesson time: 30 minutes
Exercise 5-2.1: Creating the MyDivideByZeroException classIn this exercise, you will create a custom exception that represents an illegal attempt to divide by zero.
To create the MyDivideByZeroException class
In Solution Explorer, right-click Form1 to open the code editor.
In the code editor locate the end of the Form1 class definition. Add the following code after the Form1 class definition to define a new exception class:
Visual Basic .NET
Public Class MyDivideByZeroException Inherits ApplicationException End Class
Visual C#
public class MyDivideByZeroException : ApplicationException { }
Create a constructor for your new class that calls the base class constructor and sets the message property to an informative string, as shown in the following example:
Visual Basic .NET
Public Sub New() MyBase.New("You have attempted to divide by zero!") End Sub
Visual C#
public MyDivideByZeroException() : base("You have attempted to divide by zero!") { }
From the Build menu, choose Build Solution to build, and save your work.
In this exercise, you will create a method that tests if the value passed to it is zero, and raises an exception if it is. You will then add code to call this method to test the divisor of each division operation.
To add code to raise exceptions
In the code editor, locate the Form1 End Class statement (Visual Basic .NET) or the Form1 closing } statement (Visual C#). Immediately before the end of the class, add the following method:
Visual Basic .NET
Private Sub ValidateDivisor(ByVal Divisor As Double) If Divisor = 0 Then Dim anException As New MyDivideByZeroException() Throw anException End If End Sub
Visual C#
private void ValidateDivisor(double Divisor) { if(Divisor == 0) { MyDivideByZeroException anException = new MyDivideByZeroException(); throw anException; } }
Locate the EqualsHandler method. Locate the line that reads Case Operation.Divide (Visual Basic .NET) or case Operation.Divide (Visual C#). Beneath this line, add a call to ValidateDivisor as shown below. Make a similar modification to the OperationHandler method.
Visual Basic .NET
ValidateDivisor(Double.Parse(Register1))
Visual C#
ValidateDivisor(Double.Parse(Register1));
Press Ctrl+F5 to build your application and run without debugging. Attempt to divide a number by zero. Note that application execution halts while an exception-handling box is displayed. You have the option of attempting to proceed or quitting the application immediately.
In this exercise you will add Try Catch Finally blocks to your application to handle the new exceptions. In the Catch block you will catch any MyDivideByZero exceptions and display a message that admonishes the user not to divide by zero but does not crash the program. You will leave the Finally block blank it will be used in the next lab.
To add Try Catch Finally blocks to your application
Locate the Case Operation.Divide (Visual Basic .NET) and case Operation.Divide: (Visual C#) clauses of the EqualsHandler and OperationHandler methods and modify them to resemble the following:
Visual Basic .NET
Case Operation.Divide Try ValidateDivisor(Double.Parse(Register1)) Result = Double.Parse(Register2) / Double.Parse(Register1) ' In the EqualsHandler method, this block should also contain ' the line CurrentOperation = Operation.Divide Catch ex As MyDivideByZeroException Finally End Try
Visual C#
case Operation.Divide: try { ValidateDivisor(Double.Parse(Register1)); Result = Double.Parse(Register2) / Double.Parse(Register1); // In the EqualsHandler method, this block should also contain // the line CurrentOperation = Operation.Divide; } catch (MyDivideByZeroException ex) { } finally { }
In the Catch block, add code to inform the user that an attempt was made to divide by zero and then continue with the program, as shown below:
Visual Basic .NET
MessageBox.Show("An Exception was thrown. The message was: " & _ ex.Message & "Please check your figures.")
Visual C#
MessageBox.Show("An Exception was thrown. The message was: " + ex.Message + "Please check your figures.");
Press Ctrl+F5 to build and run your application. Notice that now when you attempt to divide by zero your code in the catch block runs instead of the default exception handler.