0% found this document useful (0 votes)
4 views

Common Errors

The document outlines common programming errors, including syntax, runtime, logical, configuration, and database errors, along with examples for each type. It explains exception handling in .NET, including the use of Try...Catch...Finally blocks, custom exceptions, and logging practices for debugging and monitoring applications. Additionally, it covers configuring custom error pages in ASP.NET to improve user experience during errors.

Uploaded by

Indira pothiraj
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Common Errors

The document outlines common programming errors, including syntax, runtime, logical, configuration, and database errors, along with examples for each type. It explains exception handling in .NET, including the use of Try...Catch...Finally blocks, custom exceptions, and logging practices for debugging and monitoring applications. Additionally, it covers configuring custom error pages in ASP.NET to improve user experience during errors.

Uploaded by

Indira pothiraj
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Common Errors

 Syntax errors: Typos or grammatical mistakes in code (e.g., missing semicolon).

Ex: Dim x As Integer = 10 ' Missing semicolon


Dim 123 As Integer = 5 ' Invalid variable name
If x > 10 Then ' Missing closing parenthesis

 Runtime errors: Errors that occur during program execution (e.g., division by zero).
1. NullReferenceException:
Dim name As String = Nothing
Dim nameLength As Integer = name.Length ' Throws NullReferenceException
2. IndexOutOfRangeException:
Dim numbers() As Integer = {1, 2, 3}
Dim value As Integer = numbers(4) ' Throws IndexOutOfRangeException
3. DivideByZeroException:
Dim result As Integer = 10 / 0 ' Throws DivideByZeroException

 Logical errors: Errors in code logic leading to unexpected behavior (e.g., infinite
loop).
1. Infinite Loops:
While True
' Code that never exits the loop
End While
2. Incorrect Conditions:
If x = 10 Then
' Code that executes even if x is not 10
End If
3. Off-by-One Errors:

For i As Integer = 0 To array.Length - 1


' Code that might access array(array.Length)
Next
 Configuration errors: Mistakes in application configuration files (e.g., incorrect
connection string).
1. Incorrect Connection Strings:
XML:
<connectionStrings>
<add name="MyConnectionString" connectionString="Data
Source=MyServer;Initial Catalog=MyDatabase"
providerName="System.Data.SqlClient" />
</connectionStrings>

 Database errors: Errors connecting to or interacting with a database (e.g., invalid


credentials or table name).
1. Invalid Connection String:

Dim connection As New SqlConnection("InvalidConnectionString")

2. SQL Syntax Errors:

SELECT * FROM Customers; ' Missing WHERE clause

3. Database Access Issues:

Dim command As New SqlCommand("SELECT * FROM Customers", connection)

Dim reader As SqlDataReader = command.ExecuteReader()


The .NET Exception Object

In .NET, when an error occurs during program execution, an exception object is thrown. This
object provides valuable information about the error, including:

 Message: A human-readable description of the error.


 StackTrace: A list of methods that were called leading up to the error, helping
pinpoint its source.
 InnerException: If the exception was caused by another exception, this property holds
the inner exception.
 Source: The assembly or component where the exception originated.
 TargetSite: The method where the exception occurred.

Catching and Handling Exceptions

To handle exceptions in VB.NET, you use a Try...Catch...Finally block. The Try


block contains the code that might throw an exception. If an exception occurs, it's
caught in the Catch block, where you can handle the error appropriately.

Example:

Try
' Code that might throw an exception
Dim result As Integer = 10 / 0
Catch ex As Exception
' Handle the exception
MsgBox("An error occurred: " & ex.Message)
Finally
' Code that always executes, regardless of whether an exception occurred
End Try

Common Exception Types:

 NullReferenceException: Thrown when you attempt to access a member of a null


object.
 IndexOutOfRangeException: Thrown when you try to access an element in an array
or collection using an invalid index.
 DivideByZeroException: Thrown when you attempt to divide a number by zero.
 InvalidCastException: Thrown when you try to cast an object to an incompatible
type.
 ArgumentException: Thrown when an invalid argument is passed to a method.
 FormatException: Thrown when a string cannot be converted to a specific data type.

Custom Exceptions:

You can create custom exceptions to represent specific error conditions in your
application. This provides more meaningful error information.

Example:
Public Class MyCustomException Inherits Exception
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
End Class
Handling Exceptions

Exception handling is crucial for writing robust and user-friendly VB.NET applications.
Here's a breakdown of key concepts with syntax examples:

1. Try...Catch...Finally Block:
 This is the fundamental structure for handling exceptions.
 The Try block contains the code that might throw an exception.
 The Catch block handles specific exceptions or a general Exception type.
 The Finally block executes code regardless of whether an exception occurs.
Example:
Try
' Code that might throw an exception
Dim result As Integer = 10 / 0 ' Division by zero
Catch ex As DivideByZeroException
' Handle DivideByZeroException
MsgBox("Cannot divide by zero!")
Catch ex As Exception ' Catch any other exceptions
' Handle general exceptions
MsgBox("An error occurred: " & ex.Message)
Finally
' Code that always executes (e.g., closing resources)
' ...
End Try
2. Catching Specific Exceptions:
You can catch specific exception types in separate Catch blocks.
This allows for more tailored error handling based on the exception type.
Example:
Try
' Code that might throw different exceptions
Dim value As String = Nothing
Dim length As Integer = value.Length ' NullReferenceException
Dim numbers() As Integer = {1, 2, 3}
Dim element As Integer = numbers(4) ' IndexOutOfRangeException
Catch ex As NullReferenceException
MsgBox("You tried to access a member of a null object.")
Catch ex As IndexOutOfRangeException
MsgBox("The index you provided is out of bounds.")
End Try
3. Rethrowing Exceptions:
In some cases, you might want to rethrow an exception to let a higher-level handler deal with it.
Example:
Try
' Code that might throw an exception
Dim result As Integer = DoSomeOperation() ' Custom method
' Rethrow any exception thrown by DoSomeOperation
Throw
Catch ex As Exception
' Handle exceptions here if needed
End Try
' DoSomeOperation method
Private Function DoSomeOperation() As Integer
' Code that might throw an exception
'...
Throw New MyCustomException("An error occurred in DoSomeOperation")
End Function
4. Using Finally Block:
The Finally block always executes, even if an exception occurs.
It's commonly used to release resources (e.g., closing files, database connections).
Example:
Try
' Code that might throw an exception
Dim file As StreamWriter = New StreamWriter("myfile.txt")
file.WriteLine("Hello world!")
Catch ex As Exception
MsgBox("Error writing to file!")
Finally
' Ensure the file is closed, regardless of exceptions
If file IsNot Nothing Then
file.Close()
End If
End Try

Throwing Your Own Exceptions


While .NET provides various built-in exceptions, they might not always convey the
specific error conditions in your application. This is where custom exceptions come in handy.
Creating Custom Exceptions:
You can create custom exceptions by inheriting from the System.Exception class. This allows
you to define your own exception types with specific properties and messages.
Example:
Public Class InsufficientFundsException Inherits Exception
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
End Class
This code defines a InsufficientFundsException class that inherits from Exception. It has a
constructor that takes a message as input.
Throwing Custom Exceptions:
Once you have a custom exception class, you can throw it within your code when specific
error conditions occur.
Example:
Public Function Withdraw(ByVal amount As Decimal) As Decimal
If accountBalance - amount < 0 Then
Throw New InsufficientFundsException("Insufficient funds in your account.")
End If
accountBalance -= amount
Return accountBalance
End Function
This example shows a Withdraw function that checks for sufficient funds. If the balance is
insufficient, it throws an InsufficientFundsException with a specific message.
Catching Custom Exceptions:
In other parts of your code, you can catch the custom exception using a Try...Catch...Finally
block. This allows for tailored error handling based on the specific exception type.
Example:
Try
Dim withdrawnAmount As Decimal = account.Withdraw(100)
MsgBox("Withdrawn: " & withdrawnAmount.ToString())
Catch ex As InsufficientFundsException
MsgBox(ex.Message) ' Display the custom message
End Try
This code demonstrates catching the InsufficientFundsException and displaying its message
to the user.

Logging Exceptions

Logging is essential for debugging and monitoring .NET applications. It allows you to record
events and messages during program execution.

Identify Bugs: Custom logs pinpoint the exact cause of errors, saving you time debugging.

Performance Reviews: Logs help analyze application performance and identify bottlenecks.

Root Cause Analysis: Logs provide a detailed history of events leading up to an issue.

Logging Options:

.NET offers built-in logging providers and supports external libraries for more features:

Built-in Providers:

Console: Writes logs to the console window.

Debug: Writes logs to the debugger window.

EventLog: Writes logs to the Windows Event Log (Windows only).

EventSource: Uses Event Tracing for Windows (ETW) or LTTng for detailed logging.

Logging Levels:

.NET defines different logging levels based on severity:

Critical: System-threatening failures.

Error: Errors preventing an operation.

Warning: Potential problems requiring attention.

Information: Informational messages about application behavior.

Debug: Detailed debugging information.


Trace: Extremely detailed information (rarely used).

Logging Example:

This example uses a built-in provider (Console) to log a message:

Public Class IndexModel Inherits PageModel


Private _logger As ILogger(Of IndexModel)
Public Sub New(logger As ILogger(Of IndexModel))
_logger = logger
End Sub
Public Sub OnGet()
Try
_logger.LogInformation("Welcome to the Loggly Guide")
Catch ex As Exception
_logger.LogError(ex, "An error occurred in OnGet: {message}", ex.Message)
End Try
End Sub
End Class

6. Error Pages

Understanding ASP.NET Error Handling

By default, ASP.NET displays an uninformative "Yellow Screen of Death" (YSOD)


when an unhandled exception occurs. This can be detrimental to the user experience and
security. To provide a better experience, you can create custom error pages that handle
specific HTTP status codes and display user-friendly messages.

Configuration in web.config

The web.config file is the central location for configuring error handling in your ASP.NET
application. Here's how to configure custom error pages:

XML

<configuration>

<system.web>

<customErrors mode="RemoteOnly" defaultRedirect="~/ErrorPage.aspx">


<error statusCode="404" redirect="~/NotFound.aspx" />

<error statusCode="500" redirect="~/GeneralError.aspx" />

</customErrors>

</system.web>

</configuration>

mode Attribute:

RemoteOnly (default): Shows custom pages only to remote clients, not developers on the
local machine.

On (for development only): Shows custom pages to all clients.

Off: Disables custom error pages (not recommended).

defaultRedirect Attribute: Specifies the default error page to redirect to if no specific error
code is mapped.

Creating Custom Error Pages (.aspx Files)

Create ASP.NET Web Forms pages (.aspx) for your custom error handling. Here's an
example for the NotFound.aspx page:

HTML

<%@ Page Language="vb" %>

<!DOCTYPE html>

<html>

<head>

<title>Page Not Found</title>

</head>

<body>

<h1>Error 404: Page Not Found</h1>


<p>The page you requested was not found. Please check the URL and try again.</p>

<p>You can also go back to the <a href="/">home page</a>.</p>

</body>

</html>

Accessing Error Information (Optional)

If you need to access specific error details within your custom error page, you can use the
Server.GetLastError() method in your code-behind file (NotFound.aspx.vb in this case):

Partial Class NotFound Inherits System.Web.UI.Page

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

Dim error As Exception = Server.GetLastError()

If error IsNot Nothing Then

' Access error details (e.g., error message, stack trace)

Response.Write("Error message: " & error.Message & "<br>")

End If

End Sub

End Class

Use code with caution.

Handling Errors in Code (Using Try...Catch Blocks)

To handle errors within your ASP.NET page code, use Try...Catch blocks:

<script runat=server>

Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

Try
' Your code here

Catch ex As Exception

Response.Redirect("~/" & GeneralError.aspx.vb.Replace(".vb", ""), False)

Throw ' Re-throw to trigger custom error handling

End Try

End Sub

</script>

7. Page Tracing

Page tracing allows you to track the execution flow of your ASP.NET pages, recording
information like:

 View state information


 Control events
 Data binding details

You might also like