Common Errors
Common Errors
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:
In .NET, when an error occurs during program execution, an exception object is thrown. This
object provides valuable information about the error, including:
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
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
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:
EventSource: Uses Event Tracing for Windows (ETW) or LTTng for detailed logging.
Logging Levels:
Logging Example:
6. Error Pages
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>
</system.web>
</configuration>
mode Attribute:
RemoteOnly (default): Shows custom pages only to remote clients, not developers on the
local machine.
defaultRedirect Attribute: Specifies the default error page to redirect to if no specific error
code is mapped.
Create ASP.NET Web Forms pages (.aspx) for your custom error handling. Here's an
example for the NotFound.aspx page:
HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
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):
End If
End Sub
End Class
To handle errors within your ASP.NET page code, use Try...Catch blocks:
<script runat=server>
Try
' Your code here
Catch ex As Exception
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: