Prizes & Awards
My Profile
Active Members
TodayLast 7 Days
more...
|
Resources » Articles » .NET Framework »
Error Handling in VB.Net
|
Error Handling ============================================================================================= Three types of Errors can occur in Visual Basic project i) Syntax Errors ii) Runtime Errors iii)Logical Error ============================================================================================= Vb.Net provides two ways to handle exceptions i) Structured Exception Handling ii)Unstructured Exception Handling ============================================================================================= Structured Exception handling is a fundamental part of the CLR, and provides .NET programmers with a great way of managing errors. All the exceptions are derived from the System.Exception class. The System.Exception class is the parent class for all the exceptions. When an exception occurs in an application, the system throws the error and the error is handled through the process of structured exception handling. In Structured Exception handling, the application is divided into blocks of code. Those blocks that have the probability of raising an error contain one or more associated exception handlers. Structured exception handling uses the Try…Catch…Finally statement. ============================================================================================= ASP.Net also provides three ways of handling errors. i) Page Level Error Event ii) Application Level Error Event iii)Application Configuration File ============================================================================================= Page_Error Event At the page level you can use the Page_Error event to trap errors on a page. Application_Error Event Like the Page_Error event, there is also an Application_Error event, which is declared in the global.asax. This event will be run if no Page_Error event traps the error. Application Configuration As well as programmatic handling of errors, there is also declarative method utilizing the web.config file. This method is for handling HTTP error or error not handled elsewhere in the application, and providing a simple way to return custom error pages. It is configured with the customErrors element of the system.web section in the configuration file < system.web> < customErrors defaultRedirect=”url” mode=”On|Off|RemoteOnly”> < error statusCode=”code” redirect=”url” /> < /customErrors> < /system.web> The defaultRedirect attribute indicates the page that should be shown if no other errors are trapped. It should be the last resort page for completely unexpected errors. The mode=”On” attribute indicates that custom errors be enabled. The mode=”Off” attribute indicates that custom errors be disabled. The mode=”RemoteOnly” attribute indicates that custom errors are only enabled for remote clients. Unstructured Exception handling is not recommended since the code written by using the “On Error” statement is difficult to maintain. ============================================================================================= FAQ ============================================================================================= How to Handle Exception? Using Try, Catch and Finally Statement. ============================================================================================= What is the base class of all the exceptions that provides the basic functionality for exception handling? Exception Class ============================================================================================= What are the two main types of exception classes and their purposes? System Exception Application Exception System Exception represents the exceptions thrown by the CLR. Application Exception represents the exceptions thrown by user code. ============================================================================================= What is Try, Catch Statement? It provides mechanism for catching exceptions that occur during execution of a block. ============================================================================================= What is Finally Block? Must not contain a return statement. This statement will be executed on both error state and non-error state. ============================================================================================= Will finally block get executed if the exception had not occurred? Yes ============================================================================================= Can multiple catch blocks be executed? No ============================================================================================= What are the different exception handling approaches that can be used in ASP.Net? i) Using Try, Catch and finally block in the code. ii) Using the Error Event Procedures at the page, application or global levels. iii)Using the Server Object’s GetLastError and ClearError Methods. ============================================================================================= How to display errors using Page_Error event of Page Object? Private Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Error Respons.Write (Server.GetLastError (). ToString) Server.ClearError () End Sub ============================================================================================= How to redirect the user to the friendly error-handler page when an Application error occurs? Modify web.config as The configuration section supports an inner tag that associates HTTP status codes with custom error pages. For example: < customErrors mode="On" defaultRedirect="genericerror.htm"> < error statusCode="404" redirect="pagenotfound.aspx"/> < error statusCode="403" redirect="noaccess.aspx"/> < /customErrors> ============================================================================================= Can we handle the error and redirect to some pages using web.config? Yes, we can do this, but to handle errors, we must know the error codes; only then we can take the user to a proper error message page, else it may confuse the user. CustomErrors Configuration section in web.config file: The default configuration is: < CustomErrors mode="RemoteOnly" defaultRedirect="Customerror.aspx" > < error statusCode="404" redirect="Notfound.aspx" / > < /CustomErrors > If mode is set to Off, custom error messages will be disabled. Users will receive detailed exception error messages. If mode is set to On, custom error messages will be enabled. If mode is set to RemoteOnly, then users will receive custom errors, but users accessing the site locally will receive detailed error messages. Add an tag for each error you want to handle. The error tag will redirect the user to the Notfound.aspx page when the site returns the 404 (Page not found) error. ] ============================================================================================= What is the difference between On Error Go To 0,On Error Resume Next and On Error ErrorHandler statements? When is each of them used? You can use the “On Error Resume Next” statement to specify that when an error occurs, the control should pass to the next line of code following the line in which the error occurred. “On Error GoTo 0” statement can be used to disable any error handler in a procedure. “On Error GoTo ErrorHandler” statement specifies that when an error occurs, the control should pass to the error handler , which displays an error message to the user. =============================================================================================
Example #1:
Private Sub Page_Load (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here Dim str As System.Text.StringBuilder str.Append("Hai") ' Error Line as str is not instantiated Response. Write (str.ToString) End Sub
Private Sub Page_Error (ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Error Dim err As String = “Error in:” & Request.Url.ToString () & “ & “Stack Trace Below: ” & Server.GetLastError (). ToString () Response. Write (err) Server.ClearError () End Sub
Example #2:
Private Sub Page_Load (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here Dim str As System.Text.StringBuilder str.Append("Hai") ' Error Line as str is not instantiated Response. Write (str.ToString) End Sub
[global.asax] Private Sub Application_Error (ByVal sender As System.Object, ByVal e As System.EventArgs) Dim err As String = “Error in:” & Request.Url.ToString () & “ & “Stack Trace Below: ” & Server.GetLastError (). ToString () Response. Write (err) Server.ClearError () End Sub
Example #3:
[MainForm.aspx] Private Sub Page_Load (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here Dim str As System.Text.StringBuilder str.Append("Hai") ' Error Line as str is not instantiated Response. Write (str.ToString) End Sub
[Web.Config] < customErrors mode="RemoteOnly" defaultRedirect="Customerror.aspx" > < error statusCode="404" redirect="Notfound.aspx" / > < /customErrors > 'This will take the user to NotFound.aspx defined in IIS.
Example #4:
Sub ErrDemo() On Error GoTo ErrorHandler1 Dim A As Integer = 50 Dim B As Integer = 0 Dim C As Integer On Error GoTo 0 C = A/B B = 20 Exit Sub ErrorHandler1: MsgBox (“You are trying to perform an Invalid Operation!”) Resume Next End Sub
|
Responses
|
No responses found. Be the first to respond and make money from revenue sharing program.
|
|