Home

Error and Exception Handling

Error Handling

Introduction

In its early versions, the Visual Basic had a way to deal with errors. A run-time error is one that occurs when using your webpage. Consider the following webpage:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim number As Double
    Dim result As Double

    number = txtNumber.Text

    result = number * 24
    txtResult.Text = CStr(result)
End Sub
</script>
<title>Error Handling</title>
</head>
<body>
<form id="frmErrors" runat="server">
<h3>Error Handling</h3>

<table>
  <tr>
    <td>Number:</td>
    <td><asp:TextBox id="txtNumber" runat="server"></asp:TextBox></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td><asp:Button id="btnCalculate" Text="Calculate"
                    OnClick="btnCalculateClick" runat="server"></asp:Button></td>
  </tr>
  <tr>
    <td>Result:</td>
    <td><asp:TextBox id="txtResult" runat="server"></asp:TextBox></td>
  </tr>
</table>
</form>
</body>
</html>

Here is an example of using the webpage:

Error Handling

Error Handling

Error Handling

Here is another example of using the webpage:

Error Handling

Error Handling

If you think that a problem could occur, start by creating a label that would be used to transfer code to another section. Here is an example::

<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim number As Double
    Dim result As Double

    number = txtNumber.Text

    result = number * 24
    txtResult.Text = CStr(result)

PossibleProblem:
    lblMessage.Text = "There was a problem when executing your instructions"
End Sub
</script>

After creating such a label, you should specify when to jump to that label because you would want the label section to execute only when necessary. To do this, you can add an Exit Sub line above the label section. Here is an example:

<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim number As Double
    Dim result As Double

    number = txtNumber.Text

    result = number * 24
    txtResult.Text = CStr(result)

    Exit Sub

PossibleProblem:
    lblMessage.Text = "There was a problem when executing your instructions"
End Sub
</script>

This time if you execute the program with an appropriate value, the label section would not be reached.

In Case Of Error, Jump To Label

If a problem occurs when someone is using your webpage, a nasty error may display. When you think there will be a problem in your code, somewhere in the lines under the name of the function but before the line that could cause the problem, type On Error GoTo followed by the name of the label that would deal with the error. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
    On Error GoTo PossibleProblem

    Dim number As Double
    Dim result As Double

    number = txtNumber.Text

    result = number * 24
    txtResult.Text = CStr(result)

    Exit Sub

PossibleProblem:
    lblMessage.Text = "There was a problem when executing your instructions"
End Sub
</script>
<title>Error Handling</title>
</head>
<body>
<form id="frmErrors" runat="server">
<h3>Error Handling</h3>

<table>
  <tr>
    <td>Number:</td>
    <td><asp:TextBox id="txtNumber" runat="server"></asp:TextBox></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td><asp:Button id="btnCalculate" Text="Calculate"
                    OnClick="btnCalculateClick" runat="server"></asp:Button></td>
  </tr>
  <tr>
    <td>Result:</td>
    <td><asp:TextBox id="txtResult" runat="server"></asp:TextBox></td>
  </tr>
</table>

<asp:Label id="lblMessage" runat="server"></asp:Label>
</form>
</body>
</html>

Here is an example of running the program:

Error Handling

In Case Of Error, Jump To Line #

Although the label is more explicit, it only indicates what line to jump to in case of a problem. The alternative is to specify a line number instead of a label.

Resume

If a problem occurs in your code and you provide a label to display a friendly message as done above, a message would display and the execution would return where the problem occurred. You can provide an alternate value to continue as if nothing happened.

To indicate that the code should continue, you can use the Resume keyword. Here is an example:

<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
    On Error GoTo PossibleProblem

    Dim number As Double
    Dim result As Double

    number = CDbl(txtNumber.Text)

    Resume

    result = number * 24
    txtResult.Text = CStr(result)

    Exit Sub

PossibleProblem:
    lblMessage.Text = "There was a problem when executing your instructions"
End Sub
</script>

When an error occurs, if you want the program to continue with an alternate value than the one that caused the problem, in the label section, type Resume Next. Here is an example:

<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
    On Error GoTo PossibleProblem

    Dim number As Double
    Dim result As Double

    number = CDbl(txtNumber.Text)

    result = number * 24
    txtResult.Text = CStr(result)

    Exit Sub

PossibleProblem:
    lblMessage.Text = "There was a problem when executing your instructions"
    Resume Next
End Sub
</script>

In this case, when the execution returns to the line of code that caused the problem, it would use 0 as a substitute to the inappropriate value. You can provide an alternate value to use in case of error. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
    On Error GoTo PossibleProblem

    Dim number As Double
    Dim result As Double

    number = CDbl(txtNumber.Text)

    result = number * 24
    txtResult.Text = CStr(result)

    Exit Sub

PossibleProblem:
    lblMessage.Text = "There was a problem when executing your instructions"

    number = 10

    Resume Next
End Sub
</script>
<title>Error Handling</title>
</head>
<body>
<form id="frmErrors" runat="server">
<h3>Error Handling</h3>

<table>
  <tr>
    <td>Number:</td>
    <td><asp:TextBox id="txtNumber" runat="server"></asp:TextBox></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td><asp:Button id="btnCalculate" Text="Calculate"
                    OnClick="btnCalculateClick" runat="server"></asp:Button></td>
  </tr>
  <tr>
    <td>Result:</td>
    <td><asp:TextBox id="txtResult" runat="server"></asp:TextBox></td>
  </tr>
</table>

<asp:Label id="lblMessage" runat="server"></asp:Label>
</form>
</body>
</html>

Here is one example of using the webpage:

Error Handling

Error Handling

The Err Object

To support error handling, the Visual Basic library provides a global variable named Err. This allows you to identify the error and its description. Because an error depends on what caused it and why, the values of the Err variable also depend and are not always the same.

Exception Handling Fundamentals

Introduction

Another and better technique to deal with errors is referred to as exception handling or structured exception handling (SEH). The On Error GoTo system of dealing with errors is referred to as unstructured exception handling (or unSEH).

Trying to Catch an Error

Exception handling is essentially based on two main keywords: Try and Catch. The formula to follow is:

Try
    ' Code to execute in case everything is alright
Catch
    ' If something bad happened, deal with it here
End Try

Exception handling starts with the Try keyword. Under the Try line, Write the normal code to execute. Close the section with the Catch keyword. Here is an example:

<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim pricePerCCF As Double
    Dim monthlyCharges As Double
    Dim consumption As Double

    pricePerCCF = 50.0
    monthlyCharges = 0.0

    Try
        consumption = CDbl(txtConsumption.Text)

        If consumption >= 0.50 Then
            pricePerCCF = 35.00
        End If
    Catch

    . . .

End Sub
</script>

As code executes in the Try section, if there is a problem, the execution would "get out" of the Try section and start looking for a Catch section. Therefore, you must always have a Catch section. Close the Catch section, in fact close the exception section, with the End Try line. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim pricePerCCF As Double
    Dim monthlyCharges As Double
    Dim consumption As Double

    pricePerCCF = 50.0
    monthlyCharges = 0.0

    Try
        consumption = CDbl(txtConsumption.Text)

        If consumption >= 0.50 Then
            pricePerCCF = 35.00
        End If
    Catch
                
    End Try

    txtPricePerCCF.Text = pricePerCCF

    pricePerCCF = CDbl(txtPricePerCCF.Text)

    monthlyCharges = consumption * pricePerCCF
    txtMonthlyCharges.Text = Format(monthlyCharges, "F")
End Sub
</script>
<title>Gas Utility Company</title>
</head>
<body>
<div align="center">

<form id="frmBillPreparation" runat="server">
<h3>Gas Utility Company</h3>

<table border=0>
  <tr>
    <td>Consumption:</td>
    <td><asp:TextBox id="txtConsumption" runat="server" /></td>
  </tr>
  <tr>
    <td>&nbsp</td>
    <td style="text-align: center">
        <asp:Button id="btnCalculate"
                    text="Calculate"
                    OnClick="btnCalculateClick"
                    runat="server"></asp:Button></td>
  </tr>
  <tr>
    <td>Price Per CCF:</td>
    <td><asp:TextBox id="txtPricePerCCF" runat="server" /></td>
  </tr>
    <tr>
    <td>Monthly Charges:</td>
    <td><asp:TextBox id="txtMonthlyCharges" runat="server" /></td>
  </tr>
</table>
</form>
</div>
</body>
</html>

Trying to Catch an Error

Trying to Catch an Error

When the Catch keyword is simply written as above, it would be asked to treat any error that occurs. One problem in this case is that we may not know the type of error and why it came up. Because there can be various types of errors, you also should make your program more intuitive and friendlier so that, when an error occurs, the user would know the type of problem. This is also useful if somebody calls you and says that your webpage is not functioning right.

The Error Message

As mentioned already, if an error occurs when processing code in a Try section, the execution is transferred to the next Catch section. You can then use the catch section to deal with the error. At a minimum, you can display a message to inform the user. To do this, you can create a message box in the Catch section. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim pricePerCCF As Double
    Dim monthlyCharges As Double
    Dim consumption As Double

    pricePerCCF = 50.0
    monthlyCharges = 0.0

    Try
        consumption = CDbl(txtConsumption.Text)

        If consumption >= 0.50 Then
            pricePerCCF = 35.00
        End If
    Catch
        lblError.Text = "Something bad happened"
    End Try

    txtPricePerCCF.Text = pricePerCCF

    pricePerCCF = CDbl(txtPricePerCCF.Text)

    monthlyCharges = consumption * pricePerCCF
    txtMonthlyCharges.Text = Format(monthlyCharges, "F")
End Sub
</script>
<title>Gas Utility Company</title>
</head>
<body>
<div align="center">

<form id="frmBillPreparation" runat="server">
<h3>Gas Utility Company</h3>

<table border=0>
  <tr>
    <td>Consumption:</td>
    <td><asp:TextBox id="txtConsumption" runat="server" /></td>
  </tr>
  <tr>
    <td>&nbsp</td>
    <td style="text-align: center">
        <asp:Button id="btnCalculate"
                    text="Calculate"
                    OnClick="btnCalculateClick"
                    runat="server"></asp:Button></td>
  </tr>
  <tr>
    <td>Price Per CCF:</td>
    <td><asp:TextBox id="txtPricePerCCF" runat="server" /></td>
  </tr>
    <tr>
    <td>Monthly Charges:</td>
    <td><asp:TextBox id="txtMonthlyCharges" runat="server" /></td>
  </tr>
</table>

<asp:Label id="lblError" runat="server"></asp:Label>

</form>
</div>
</body>
</html>

The Error Message

The Error Message

Of course, you should create a more meaningful and clearer message.

Fundamentals of Exceptions in the .NET Framework

The Exception Class

To support exception handling, the .NET Framework provides a special class called Exception. When the execution encounters an error, the Exception class allows you to identify the type of error and take an appropriate action.

Normally, Exception mostly serves as the general class of exceptions. It is used like a Catch that is not followed by any parameter. Various classes are derived from Exception to be able to deal with various types of errors. As a result, almost any type of exception you may encounter already has a class created to deal with it.

There are so many exception classes that we cannot study or review them all. The solution we will use is to introduce or review a class when we meet its type of error.

In exception handling, errors are dealt with in the Catch clause. To use it, on the right side of Catch, type a parameter name, followed by the As operator, and followed by the type of exception you want to deal with. By default, an exception is first of type Exception. Based on this, a typical formula to implement exception handling is:

Try

    ' Process the normal flow of the program here

Catch ex As Exception

    ' Deal with the exception here

End Try

As reviewed already, when an exception occurs in the Try section, code execution is transferred to the Catch section. If you declare the exception as an Exception type, this class will identify the error.

The Exception's Message

One of the properties of the Exception class is called Message. This property contains a string that describes the type of error that occurred. You can then use this Exception.Message property to display an error message if you want. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim number As Double
    Dim result As Double

    Try
        number = txtNumber.Text
    Catch ex As Exception
        lblMessage.Text = ex.Message
    End Try

    result = number * 24
    txtResult.Text = CStr(result)

    Exit Sub

PossibleProblem:
    lblMessage.Text = "There was a problem when executing your instructions"
End Sub
</script>
<title>Error Handling</title>
</head>
<body>
<form id="frmErrors" runat="server">
<h3>Error Handling</h3>

<table>
  <tr>
    <td>Number:</td>
    <td><asp:TextBox id="txtNumber" runat="server"></asp:TextBox></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td><asp:Button id="btnCalculate" Text="Calculate"
                              OnClick="btnCalculateClick" runat="server"></asp:Button></td>
  </tr>
  <tr>
    <td>Result:</td>
    <td><asp:TextBox id="txtResult" runat="server"></asp:TextBox></td>
  </tr>
</table>

<asp:Label id="lblMessage" runat="server"></asp:Label>
</form>
</body>
</html>

Here is an example of using the webpage:

Fundamentals of Exceptions in the .NET Framework

Fundamentals of Exceptions in the .NET Framework

Custom Error Messages

As you can see, one of the strengths of the Message property is that it gives you a good indication of the type of problem that occurred. Sometimes, the message provided by the Exception class may not appear explicit enough. In fact, you may not want to show it to the user since, as in this case, the user may not understand what the message means and why it is being used. As an alternative, you can create your own message and display it to the user. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim pricePerCCF As Double
    Dim monthlyCharges As Double
    Dim consumption As Double

    pricePerCCF = 50.0
    monthlyCharges = 0.0

    Try
        consumption = CDbl(txtConsumption.Text)

        If consumption >= 0.50 Then
            pricePerCCF = 35.00
        End If
    Catch exc As Exception
        lblMessage.Text = "Please provide a valid value for the gas consumption."
    End Try

    txtPricePerCCF.Text = pricePerCCF

    pricePerCCF = CDbl(txtPricePerCCF.Text)

    monthlyCharges = consumption * pricePerCCF
    txtMonthlyCharges.Text = Format(monthlyCharges, "F")
End Sub
</script>
<title>Gas Utility Company</title>
</head>
<body>
<div align="center">

<form id="frmBillPreparation" runat="server">
<h3>Gas Utility Company</h3>

<table border=0>
  <tr>
    <td>Consumption:</td>
    <td><asp:TextBox id="txtConsumption" runat="server" /></td>
  </tr>
  <tr>
    <td>&nbsp</td>
    <td style="text-align: center">
        <asp:Button id="btnCalculate"
                    text="Calculate"
                    OnClick="btnCalculateClick"
                    runat="server"></asp:Button></td>
  </tr>
  <tr>
    <td>Price Per CCF:</td>
    <td><asp:TextBox id="txtPricePerCCF" text="0.00" runat="server" /></td>
  </tr>
    <tr>
    <td>Monthly Charges:</td>
    <td><asp:TextBox id="txtMonthlyCharges" text="0.00" runat="server" /></td>
  </tr>
</table>

<asp:Label id="lblMessage" runat="server"></asp:Label>

</form>
</div>
</body>
</html>

Here is an example of using the webpage:

Custom Error Messages

Custom Error Messages

Custom Error Messages

You can also combine the Exception.Message message and your own message. Here is an example:

<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim pricePerCCF As Double
    Dim monthlyCharges As Double
    Dim consumption As Double

    pricePerCCF = 50.0
    monthlyCharges = 0.0

    Try
        consumption = CDbl(txtConsumption.Text)

        If consumption >= 0.50 Then
            pricePerCCF = 35.00
        End If
    Catch exc As Exception
        lblMessage.Text = exc.Message & " You must provide a valid value for the gas consumption."
    End Try

    txtPricePerCCF.Text = pricePerCCF

    pricePerCCF = CDbl(txtPricePerCCF.Text)

    monthlyCharges = consumption * pricePerCCF
    txtMonthlyCharges.Text = Format(monthlyCharges, "F")
End Sub
</script>

Here is an example of using the webpage:

Custom Error Messages

Custom Error Messages

Custom Error Messages

A Review of .NET Exception Classes

Introduction

The .NET Framework provides various classes to handle almost any type of exception you can think of. There are two main ways you can use one of the exception-oriented classes of the .NET Framework. If you know for sure that a particular exception will be produced, pass its name to the Catch clause and display a custom message. The second option you have consists of throwing an exception. We will study that later.

An InvalidCast Exception

We already know that everything the user types into a webpage using the keyboard is primarily a string and it must be converted to the appropriate type before using it. When you request a specific type of value from the user, after the user has typed it and you decide to convert it to the appropriate type using one of the built-in conversion functions (CDbl(), CInt(), CDate(), CSng(), CDec(), etc), if your conversion fails, the webpage produces (we use the verb "to throw") an error. The error is from the InvalidCastException class.

An Exception From Overflowing

To better manage a value submitted to a form, an appropriate amounts of computer memory space must be allocated to store a value. If the value is higher than allowed by the data type for the variable, the webpage would produce an error. This type of error is handled by the OverflowException class.

The Exception Resulting From Formatting a Value

When declaring a variable, you usually indicate the type of value that it must store. If another type of value is handed to the variable, the browser would produce a value. The error produced from a value that is not appropriate to the expected type is handled by a class named FormatException. This is the perfect class to use with webcontrols that expect a number or a date/time value.

The Exception From Dividing By Zero

Division by zero is an operation to always avoid. The .NET Framework provides a class to face this operation. If an attempt to divide a value by 0, the browser would produce an error handled by the DivideByZeroException class.

Techniques of Using Exceptions

Handling Different Exceptions

If you judge it necessary, you can put all your executing code in a single exception handling section. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim cost = 0
    Dim period = 1
    Dim bookValue = 0.0
    Dim salvageValue = 0.0
    Dim estimatedLife = 0.0
    Dim depreciationRate = 0
    Dim row As New TableRow()
    Dim yearlyDepreciation = 0.0
    Dim column As New TableCell()

    Try
        cost = txtCost.Text
        salvageValue = txtSalvageValue.Text
        estimatedLife = txtEstimatedLife.Text
 
        depreciationRate = 100.0 / estimatedLife
        yearlyDepreciation = SLN(cost, salvageValue, estimatedLife)

        bookValue = cost

        lblDepreciation.Visible = True

        column.Text = "<b>Year</b>"
        column.Width = 80
        row.Cells.Add(column)

        column = New TableCell()
        column.Text = "<b>Depreciation Rate</b>"
        column.Width = 120
        row.Cells.Add(column)
        tblDepreciations.Rows.Add(row)

        column = New TableCell()
        column.Text = "<b>Yearly Depreciation</b>"
        column.Width = 120
        row.Cells.Add(column)
        tblDepreciations.Rows.Add(row)

        column = New TableCell()
        column.Text = "<b>Book Value</b>"
        column.Width = 100
        row.Cells.Add(column)
        tblDepreciations.Rows.Add(row)

        column = New TableCell()
        column.Text = "<b>Accumulated Depreciation</b>"
        column.Width = 100
        row.Cells.Add(column)
        tblDepreciations.Rows.Add(row)

        Do
            row = New TableRow()

            column = New TableCell()
            column.Text = period
            row.Cells.Add(column)
            tblDepreciations.Rows.Add(row)

            column = New TableCell()
            column.Text = depreciationRate & "%"
            row.Cells.Add(column)
            tblDepreciations.Rows.Add(row)

            column = New TableCell()
            column.Text = FormatNumber(yearlyDepreciation)
            row.Cells.Add(column)
            tblDepreciations.Rows.Add(row)

            column = New TableCell()
            column.Text = FormatNumber(Format(bookValue - (yearlyDepreciation * period), "#,000"))
            row.Cells.Add(column)
            tblDepreciations.Rows.Add(row)

            column = New TableCell()
            column.Text = Format(yearlyDepreciation * period, "#,000")
            row.Cells.Add(column)
            tblDepreciations.Rows.Add(row)

            period += 1
        Loop Until period = estimatedLife + 1
    Catch

    End Try
End Sub
</script>
<style>
#container
{
    margin: auto;
    width:  400px;
}
</style>
<title>Depreciation: The Straight-Line Method</title>
</head>
<body>
<form id="frmBusiness" runat="server">
<div id="container">

<h3>Straight-Line Method</h3>

<table>
  <tr>
    <td><b>Asset Original Value:</b></td>
    <td><asp:TextBox id="txtCost" Width="75px" runat="server"></asp:TextBox></td>
  </tr>
  <tr>
    <td><b>Salvage Value:</b></td>
    <td><asp:TextBox id="txtSalvageValue" Width="55px" runat="server"></asp:TextBox></td>
  </tr>
  <tr>
    <td><b>Estimated Life:</b></td>
    <td><asp:TextBox id="txtEstimatedLife" Width="55px" runat="server"></asp:TextBox>
        <asp:Button id="btnCalculate" Text="Calculate"
        	    OnClick="btnCalculateClick" runat="server" /></td>
  </tr>
</table>

<p><b><asp:Label id="lblDepreciation" Visible="false" Text="Depreciation Schedule" runat="server"></asp:Label></b></p>

<asp:Table id="tblDepreciations" runat="server" BorderColor="#333333" BorderStyle="Double" BorderWidth="2pt" GridLines="Both"></asp:Table>
</div>
</form>
</body>
</html>

Otherwise, you can create as many exception sections as you want. Here are examples:

<html>
<head runat="server">
<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim periods = 1
    Dim payment = 0.00
    Dim interestRate = 0.00
    Dim loanAmount = 0.00
    
    Try
        loanAmount = txtLoanAmount.Text
    Catch
    End Try

    Try
        interestRate = CDbl(txtInterestRate.Text) / 100.00
    Catch
    End Try

    Try
        periods = txtPeriods.Text
    Catch
    End Try

    payment = Pmt(interestRate / 12.00, periods, -loanAmount, 0.00, DueDate.EndOfPeriod)

    txtLoanAmount.Text = Format(loanAmount, "C")
    txtPayment.Text = Format(payment, "c")

End Sub
</script>
<style>
#container
{
    margin: auto;
    width:  345px;
}
</style>
<title>Business Mathematics - Musical Instrument Financing</title>
</head>
<body>
<form id="frmBusiness" runat="server">
<div id="container">

<h3>Business Mathematics</h3>
<h4>Musical Instrument Financing</h4>

<table>
  <tr>
    <td style="width: 140px"><b>Loan Amount:</b></td>
    <td><asp:TextBox id="txtLoanAmount" Width="75px" runat="server"></asp:TextBox></td>
  </tr>
  <tr>
    <td><b>Interest Rate:</b></td>
    <td><asp:TextBox id="txtInterestRate" Width="55px" runat="server"></asp:TextBox>%</td>
  </tr>
  <tr>
    <td><b>Number of Periods:</b></td>
    <td><asp:TextBox id="txtPeriods" Width="55px" runat="server"></asp:TextBox>Months
        <asp:Button id="btnCalculate" Text="Calculate"
        	    OnClick="btnCalculateClick" runat="server" /></td>
  </tr>
  <tr>
    <td style="width: 140px"><b>Loan Payment:</b></td>
    <td><asp:TextBox id="txtPayment" Width="75px" runat="server"></asp:TextBox>/Month</td>
  </tr>
</table>
</div>
</form>
</body>
</html>

Catching Various Exceptions

A code section with various or complex operations and requests can also produce different types of errors. If that's the case, you should be able to face different problems and deal with them individually, each by its own kind. To do this, you can create different Catch sections, each made for a particular error. The formula to follow is:

Try
    ' Code to Try
Catch One Type of Exception
    ' One Exception
Catch Another Type Of Exception
    ' Another Exception
End Try

The execution would proceed in a top-down:

  1. Following the normal flow of the code, the execution enters the Try block
  2. If no exception occurs in the Try block, the rest of the Try block is executed
    If an exception occurs in the Try block, the execution registers the type of error that occurred. If there is a throw line, the execution registers it also:
    1. The execution gets out of the Try section
    2. The execution examines the first Catch. If the first Catch matches the thrown error, that catch executes and the exception handling routine may seize. If the first Catch doesn’t match the thrown error, the execution proceeds with the next Catch
    3. The execution checks the next match, if any, and proceeds as in the first catch. This continues until the execution finds a Catch section that matches the thrown error
    4. If one of the catch sections matches the thrown error, its body executes. If no Catch section matches the thrown error, the execution calls the Exception class and uses the default message

Multiple catch sections are written if or when a try block is expected to throw different types of errors.

Nesting an Exception

You can create an exception inside another exception. This is referred to as nesting. In the same way, you can nest many exceptions inside of another. Here is an example:

<html>
<head runat="server">
<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim periods As Integer = 1
    Dim loanAmount As Double
    Dim regularPayment = 0.00
    Dim principalPayment = 0.00
    Dim interest = 0.00, interestRate = 0.00
    
    
    Try
        Try
            loanAmount = CDbl(txtLoanAmount.Text)
        Catch
            lblMessage.Text = "You must provide a valid value for the amount of the loan."
        End Try

        Try
            interest = CDbl(txtInterestRate.Text)
        Catch
            lblMessage.Text = "The amount you provided for the interest rate is not valid."
        End Try

        Try
            periods = CInt(txtPeriods.Text)
        Catch
            lblMessage.Text = "Please provide an appropriate number of months (number of periods) as the length of the loan."
        End Try

        interestRate = interest / 100.00

        loanAmount = Pmt(interestRate / 12.00, periods, -loanAmount, 0.00, DueDate.EndOfPeriod)
        principalPayment = PPmt(interestRate / 12.00, 1, periods, -loanAmount, 0.00, DueDate.EndOfPeriod)

        txtLoanAmount.Text = Format(loanAmount, "currency")
        txtLoanPayment.Text = Format(loanAmount, "CURRENCY")
        txtPrincipalPayment.Text = Format(principalPayment, "Currency")
    Catch
        lblMessage.Text = "Something is wrong in the code of this webpage."
    End Try
End Sub
</script>
<style>
#container
{
    margin: auto;
    width:  345px;
}
</style>
<title>Business Mathematics - Boat Financing</title>
</head>
<body>
<form id="frmBusiness" runat="server">
<div id="container">

<h3>Business Mathematics - Boat Financing</h3>

<table>
  <tr>
    <td style="width: 140px"><b>Loan Amount:</b></td>
    <td><asp:TextBox id="txtLoanAmount" Width="75px" runat="server"></asp:TextBox></td>
  </tr>
  <tr>
    <td><b>Interest Rate:</b></td>
    <td><asp:TextBox id="txtInterestRate" Width="55px" runat="server"></asp:TextBox>%</td>
  </tr>
  <tr>
    <td><b>Number of Periods:</b></td>
    <td><asp:TextBox id="txtPeriods" Width="55px" runat="server"></asp:TextBox>Months
        <asp:Button id="btnCalculate" Text="Calculate" OnClick="btnCalculateClick" runat="server" /></td>
  </tr>
  <tr>
    <td style="width: 140px"><b>Loan Payment:</b></td>
    <td><asp:TextBox id="txtLoanPayment" Width="75px" runat="server"></asp:TextBox>/Month</td>
  </tr>
  <tr>
    <td style="width: 140px"><b>Principal Payment:</b></td>
    <td><asp:TextBox id="txtPrincipalPayment" Width="75px" runat="server"></asp:TextBox>/Month</td>
  </tr>
</table>
<asp:Label id="lblMessage" runat="server"></asp:Label>

</div>
</form>
</body>
</html>

Throwing an Exception

As mentioned above, the Exception class is equipped with a Message property that carries a message for the error that occurred. We also mentioned that the message of this property may not be particularly useful to a user. Fortunately, you can create your own message and pass it to the Exception. To be able to receive custom messages, the Exception class provides the following constructor:

Public Sub New(message As String)

To use it, in the section that you are anticipating the error, type the Throw keyword followed by a new instance of the Exception class using the constructor that takes a string. The formula to follow is:

Throw [ expression ]

Previous Copyright © 2004-2016, FunctionX Next