Showing posts with label Error. Show all posts
Showing posts with label Error. Show all posts

Tuesday, January 6, 2009

Error Handing in .Net FAQ

1. How to prevent errors at design time?

VB.Net offers the Option Strict and Option Explicit statements to prevent errors at design time.

• Option Explicit :

Prevent errors at design time. It forces explicit declaration of all variables at the module level

Syntax Option

Option Explicit On.

By default it is off.

We can set option explicit in .aspx page in the page directive




• Option strict :

Enabling Option Strict causes errors to be raised if you attempt a data type conversion that leads to a loss in data.


2.What Precisely is an Exception?

The Exception Class is a member of System NameSpace and base class for all the exceptions.

2 subclasses of Exception class are System Exception Class and Application Exception class.

Exception Class
System Exception Application Exception

The SystemException class defines the base class for all .NET predefined exceptions

3.What are the properties of Exception Object ?

Source : Gets the naem of the application or the object that causes the error
Message :Gets a message that describes the current exception.
StackTrace : Gets a string representation of the frames on the call stack at the time the current exception was thrown.
InnerException : Gets the Exception instance that caused the current exception
TargetSite : Gets the method that throws the current exception.
HelpLink :Gets or sets a link to the help file associated with this exception.

4.What is Structured and UnStructured Error Handling?

Unstructured Error Handling:


Unstructured error handling is implemented with the On Error statement, which is placed at the beginning of a code block to handle all possible exceptions that occur during the execution of the code. All Visual Basic 6.0 error handlers in .NET are objects that can be accessed by using the Microsoft.VisualBasic.Information.Err namespace. The handler is set to Nothing each time the procedure is called. You should place only one On Error statement in each procedure, because additional statements disable all previous handlers that are defined in that procedure.

On Error { GoTo [ line 0 -1 ] Resume Next }

Structured Error Handling :

With structured error handling, Visual Basic now has an effective way to prevent unexpected errors from terminating the execution of the application. Structured error handling also provides the programmers with a simpler way to create robust applications that are easier to maintain. Structured error handling is implemented in Visual Basic. NET or Visual Basic 2005 with a Try...Catch...Finally block of statements. The Try...Catch...Finally block provides, for the first time to Visual Basic, the capability of nested error handling.

5. Mention Predefined exceptions provided by .net run time?


Exception --Object--Base class for all exceptions.
SystemException--Exception--Base class for all runtime-generated errors.
IndexOutOfRangeException--SystemException--Thrown by the runtime only when an array indexed improperly.
NullReferenceException--SystemException--Thrown by the runtime only when a null object
referenced.

InvalidOperationException--SystemException--Thrown by methods when in an invalid state.

ArgumentException --SystemException--Base class for all argument exceptions.

ArgumentNullException --ArgumentException--Thrown by methods that do not allow
an argument to be null.
ArgumentOutOfRangeException --ArgumentException --Thrown by methods that verify
that arguments are in a given range.

ExternalException--SystemException--Base class for exceptions that occur or are targeted
at environments outside the runtime.

ComException--ExternalException--Exception encapsulating COM HRESULT information.

SEHException --ExternalException--Exception encapsulating Win32 structured exception handling information

6.What class we need to inherit to create custom Excepton class.
To create a custom exception we must inherit from the ApplicationException class

7.How to redirect the user to the friendly error-handler page when an Application error occurs?

Modify web.config as


customErrors mode="On" defaultRedirect="errorpage.aspx"

The configuration section supports an inner tag that associates HTTP status codes with custom error pages. For example:

--< mode="On" defaultredirect="genericerror.htm">
-- < statuscode="404" redirect="pagenotfound.aspx">
--< statuscode="403" redirect="noaccess.aspx">
--< /customerrors>







Error Handling in asp.net


The Error handling model in asp.net lets you handle errors at 3 different levels

Method Level
Page Level
Application Level


Method Level:

We use Method level error handling for all the recoverable errors.
For non recoverable errors it goes to next level.

For the all the errors which can be handled we use

Try…Catch blocks

For throwing any message if an error occurred or any exception we use .

Throw… block

To clean up the error we use

Finally… block


Syntax:

Try

‘’..code for execution

Catch ex as Exception

‘’..handle the error

Finally

‘clear the error

End try



Try block contains the code need to be implemented ,
Catch block is used to handle the error
Finally block used to clear the error.


Let us suppose we are using database connection in the code and if the error occurs in the query .net framework doesn’t close the database connections. I this case we need to write the code in the FINALLY block to close he connection.


Page Level:

We use Page Level event handling when we want to trap the errors occurred in the page and redirect the user to another page which the displays the error details.

Implementation:

Write required code in the Page_Error event handler of the page.

The Page_Error event of the ASP.NET Page object is raised any time an unhandled error occurs in a page


Use GetLastError method to get reference to the latest error occurred


Set the ErrorPage property of the page object to the URL of the page which need to display the error details

The page will be redirected to the url mentioned when any unhandled error occurs.


Add error number,message to the query string in the URL.
Dim lastError As Exception

'get the last error that occurred

lastError = Server.GetLastError( )
Page.ErrorPage = "Errorpage.aspx"?errMessage=" & lastError.Message &errnumber=" & lastError.number

  • When any Unhandled error occurred in the page level ,Page_Error event is triggered and the page will be redirected to the error page mentioned with all the details of the error in the query string.
  • If we don’t add any Query string parameters,.NET will assign one for usi.e aspxerrorpath which gives relative path of the error message.

Application Level: If we want to Log all the errors raised in an application in Single location we use application level error handling. Add Page_Error event handler to the page to throw the error to next level i.e application level Add Application_error event handler in global.asax file to perform logging and redirection
To process errors at the application level, each page must include the Page_Error event handler with a single line of code to rethrow the last exception that occurred.

Private Sub Page_Error(ByVal sender As ObjectByVal e As System.EventArgs) Handles MyBase.Error 'Rethrow the last error that occurred

Throw Server.GetLastError( )

End Sub

***********Error handling in Application_error

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)

Const EVENT_LOG_NAME As String = "Application"

Dim lastException As Exception

Dim Log As EventLog

Dim message As String

'get the last error that occurred

lastException = Server.GetLastError( )

'create the error message from the message in the last exception along 'with a complete dump of all of the inner exceptions (all exception 'data in the linked list of exceptions)

message = lastException.Message & lastException.ToString( )

'Insert error information into the event log

Log = New EventLog

Log.Source = EVENT_LOG_NAME

Log.WriteEntry(message,EventLogEntryType.Error)

'perform other notifications, etc. here

'clear the error and redirect to the page used to display the 'error information

Server.ClearError( )

Response.Redirect("Errorpage.aspx?errMessage=" & lastException.Message _)

End Sub