header image

Archive for 13732

Types of Error
1. Configuration Errors:
Occur when the syntax or structure of a configuration files i.e. web.config, machine.config is incorrect. These are XML files where the nodes and the hierarchies of the nodes and/or attributes may be incorrect.

2. Parser Errors:
Occur when the ASP.NET syntax on a page is malformed due to invalid tags. The parsing of the ASP.NET pages takes place just before execution. The page could not be parsed by the parser and prevent it from being compiled.
These errors are usually of type HttpParseException. Such errors will not be caught by the Page level handler as page parsing happens before ASP.NET creates the assembly for the aspx page. Thus, such errors will have to be handled in the application scope.

If one page is started with <Script runable=”server”> but not ended with </Script>, it this case parser errors prevent a page from being compiled.

<script Runat=”Server”>
Sub Page_Load
  Label1.Text = “hello!”
End Sub

<head><title>Parsing Error Page</title></head>
<asp:Label ID=”label1″ Runat=”Server” />

3. Compilation Errors:
It’s raised by a particular language being used to compile the page when the page is in the process of execution. Occur when statements in a page’s target language are incorrect.

4. Runtime Errors:
It is not detected until the page actually executes. Occur during a page’s execution, even though the errors could not be detected at compile time

A. Handling Errors in Web Application; Redirecting to the Error Page
When errors occur in an ASP.NET application, they either get handled or propagates unhandled to higher scopes. When an unhandled exception propagates, the user may be redirected to an error page using different ASP.NET configuration settings.
There are two different scopes where we could specify which page the user should be redirected to, when errors go unhandled:

1. Page level
It is implemented through the “errorPage” attribute of the Page declarative of the webform which is applicable to single page only.

2. Application level
This applies to errors that happen anywhere in the application. This is done by the “customErrors” tag in web.config file.

1. Page Level
Customizing Error for a particular Page; Using Page declarative of an ASP.NET (.aspx) page
The errorPage attribute maps to the Page.ErrorPage property, and hence may be set programmatically. The value may optionally include query string parameters. If no parameters are added, ASP.NET would automatically add one with the name aspxerrorpath. This parameter would hold the value of the relative URL to this page, so that the error page would be able to determine which page caused the error.

If a value is specified in this attribute (or property) and an unhandled exception occurs in the page, the Page class would automatically perform a redirect to the specified page. If a value is not specified, the exception is assumed to be unhandled, wrapped in a new HttpUnhandledException and then thrown, propagating it to the next higher level.

<@ Page errorPage=”Error.htm” language=”C#” Codebehind=”Default.aspx.cs” AutoEventWireup=”false”>

2. Application Level
Customizing Error Pages with web.config; Handling Errors by setting in Configuration file
Depending on the circumstances, the application errors can be handled in different ways.

    <customErrors mode=”RemoteOnly” defaultRedirect=”/genericerror.htm”>
      <error statusCode=”500″ redirect=”/error/helpdesk.htm”/>
      <error statusCode=”404″ redirect=”/error/notfound.aspx”/>
      <error statusCode=”403″ redirect=”/error/noaccess.aspx”/>
    <compilation debug=”true”/>

    <customErrors mode=”RemoteOnly” defaultRedirect=”/genericerror.htm”>

Indicates whether custom errors are enabled, disabled, or only to be shown to remote computers. There are three error modes in which an ASP.NET application can work:

1)       Off Mode
2)       On Mode
3)       RemoteOnly Mode

The Error mode attribute determines whether or not an ASP.NET error message is displayed. By default, the mode value is set to “RemoteOnly”.

Off Mode
When the error attribute is set to “Off”, ASP.NET uses its default error page for both local and remote users in case of an error.

On Mode
In case of “On” Mode, ASP.NET uses user-defined custom error page instead of its default error page for both local and remote users. If a custom error page is not specified, ASP.NET shows the error page describing how to enable remote viewing of errors.

RemoteOnly Mode
ASP.NET error page is shown only to local users. Remote requests will first check the configuration settings for the custom error page or finally show an IIS error.

Indicates the default URL to which a browser should be redirected if an error occurs. This attribute is optional. 

      <error statusCode=”404″ redirect=”/error/notfound.aspx”/>

HTTP status code of errors for which the custom error page should be used.
Examples: 403 Forbidden, 404 Not Found, or 500 Internal Server Error. 
Redirect URL to which the client browser should be redirected if an error occurs

Only files mapped to the aspnet_isapi.dll extension in IIS generate these errors. Files not served through the aspnet_isapi.dll are not processed by ASP.NET and generate IIS errors. Regarding this case we need to consider about the IIS Errors too.

    <compilation debug=”true”/>
More information displayed on the page for error.
B. Handling Errors Programmatically; Catching Unhandled exception

There are two different scopes where we could specify which page the user should be redirected to, when errors go unhandled:

The errors can be handled in code, at either the page level or the application level.

1)      Application Level Error Handling: using Application_Error sub-routine in global.aspx file
2)      Page Level Error Handling: using Page_Error sub-routine in page

These events are raised whenever we have an unhandled exception occur within our application. If a Page_Error event is present within an ASP.NET page, and an unhandled error occurs, the event is raised. Application_Error is slightly different. It is raised for all unhandled exceptions in our ASP.NET application and is implemented in global.asax or within an HTTP Module.
Both of these events are extremely useful since they allow us a final opportunity to execute code before sending the caller an HTTP redirect to the named ASP.NET error page. Examples of their usefulness include logging the error to the Event Log or sending e-mail to the administrator depending upon the nature of the exception.

The Page base class exposes a Page_Error method, which can be overridden in a pages. The method is called whenever an uncaught exception is thrown at run time.
Page Objects Error Event

1. Page Level
In a Page using Page_Error sub-routine
The Page object has an error event that is fired when an unhandled exception occurs in the page. It is not fired if the exception is handled in the code for the page.
Sample code snippet:

Sub Page_Error(sender as Object, e as EventArgs)

  dim PageException as string = Server.GetLastError().ToString()
  dim strBuild as new StringBuilder()


End Sub 

<script language=”C#” runat=”server”>
void Page_Error(Object source, EventArgs e) {
    String message = Request.Url.ToString() + “<br>” +Server.GetLastError().ToString() ;



2. Application Level
Application Level Error Handling using Application_Error subroutine of global.asax
The Application_Error event of the global.asax is fired when an exception occurs in the corresponding web application.

Sub Application_Error(sender as Object, e as EventArgs)
  ‘Do Something
End Sub 

Unfortunately the EventArgs in this instance are unlikely to be sufficiently informative but there are alternative avenues including that introduced in the code of the last section – the HttpServerUtility.GetLastError method which returns a reference to the last error thrown in the application. This can be used as follows:

Sub Application_Error(sender as Object, e as EventArgs)
  dim LastException as string = Server.GetLastError().ToString()
End Sub 

The ClearError method of the Context class clears all exceptions from the current request – if it is not cleared the normal exception processing and consequent presentation will still occur.

Alternatively there is the HttpContext’s class Error property which returns a reference to the first exception thrown for the current HTTP request/ response.
An example:

Sub Application_Error(sender as Object, e as EventArgs)
  dim LastException as string = Context.Error.ToString()
  Response.Redirect(“CustomErrors.aspx?Err=” & Server.UrlEncode(LastException))
End Sub 

This illustrates one method for handling application errors – redirection to a custom error page which can then customize the output to the user dependent on the actual error received.

The customErrors element of the web.config file is the last line of defense against an unhandled error. If the other error handlers are in place, like the Application_Error, Page_Error subs, these will get called first. Provided they don’t do a Response.Redirect or a Server.ClearError, it should be brought to the page(s) defined in the web.config.

Local error handling; Structured Exception Handling
What is Exception?
An exceptional condition that arises during the processing of statements and expression when the application cannot be completed normally is termed as exceptions.

For example, an integer division operation throws a System.DivideByZeroException if the denominator is zero.
A throw statement throws an exception immediately and unconditionally. Control never reaches the statement immediately following the throw.
Handling Exception
The .Net framework implements structured exception handling. The term structured means that the code that has the potential to cause an exception and also it’s organized in structured blocks. The Try…Catch…End Try statement for this purpose. The syntax is as follows:

‘ Executable statements

Catch [optional filters]
‘ Statements that are to be executed when an exception occurs go here.

‘ Code placed here is executed after the code in the Try block
‘ or in the Catch block is executed. This block is optional.

End Try

Handling Exception using Custom-Exception
For implementing custom Exception Handling we need to derive the class CustomException from the system base class ApplicationException. In general, for customizing Exception Handling the following components may be necessary:
• A custom exception class which would host the exception thrown and can be thrown as a new exception
• A message class that would host all user-friendly application messages that needs to be displayed.
• The original i.e. exception will be wrap up to the customized one.
• Should filing an incident with a trouble ticketing system
• It should be configurable to allow for flexibility across policies and types

Structured Exception Handling
Structured exception handling operates on the level of procedures. Each procedure in the program should contain exception handling code designed to catch the types of exceptions that the procedure might generate. If a procedure generates an unhandled exception, it is passed up the call stack to the caller.
The ability to filter the Catch statement is an essential part of .Net’s structured exception handling. A Catch block is written like this:

Catch ex As Exception

Within the Catch block, the object ex, an instance of the System.Exception class, will contain information about the exception.

Catch ex As ExceptionType

The finally block is always executed, no matter what happens in the Try and Catch sections. This can be used for the actions that have to be performed regardless of whether an exception was thrown, such as closing files. The finally block is executed even if the thrown exception was not caught by any of the Catch statements.

Filtering exceptions could be done based on the exception type.

Catch ex As ExceptionType When Expression
Getting Exception Information

The exception class has several properties and methods.

• Source property: The Source property of the exception class is intended to hold the application or object name generating the exception. It can also be programmatically set, but if it is not set, the property returns the assembly name where the exception occurred.

• Message property: The Message property is a string containing a description of the current exception.

• TargetSite property: The TargetSite property is a string containing the name of the procedure where the exception occurred.

• GetType method: The GetType method is inherited from the System.Object class and returns the type of exception that has occurred.

• ToString method: The ToString method returns a string describing the current exception including information provided by several other exception class properties and methods.

Exception Handling as an Enterprise Library for commonly used in an Application

The Enterprise Library for Exception Handling lets developers and policy makers create a consistent strategy for processing exceptions that occur throughout the architectural layers of enterprise applications.

a)      It works as an application’s architectural layers

b)      It enables exception-handling policies to be defined and maintained at the administrative level so that policy makers, who may be system administrators as well as developers, can define how to handle exceptions. They can maintain and modify the sets of rules that govern exception handling without changing the block’s application code.

c)      It is for commonly used exception-handling functions having the ability to log exception information, sending information as notification to the administrators and developers of an application, the ability to hide sensitive information by replacing the original exception with another exception, and the ability to add contextual information to an exception by wrapping the original exception inside another exception.

d)      It lets developers create their own exception handlers.

e)      It invokes exception handlers in a consistent manner. This means that the handlers can be used in multiple places in and across applications.

f)        Every exception that is defined within the .NET framework derives from a class called Exception. This class is used to describe a general error, whose specificity is not known. For example, a general exception could be an error that is not related in any way to errors that can occur from a library you are using. 

g)      Every exception inherits from the base class Exception in order to provide a more specific response to the developer.

Exception Handling
General Practice and Issues
o Generally the same logging code is pasted through out the application in catch block
o Problem with consistency for exception handling; it varied developer to developer and application to application
o Changing policies regarding exception handling results in source code changes
o When to throw exception
Designing Threat
Exceptions that are allowed to propagate to the client can reveal internal implementation details that not make sense to the end users but are useful to attackers.

Designing Guideline and Best Practices

• Think thoroughly and set the strategy accordingly
Think the exception handling strategy thoroughly before preparing custom exception class or an Enterprise Application Library.

• Handle all the expected exceptions
Use exception handling through out the application code base.

Naming Guideline
• Name appropriately
Any new exception classes are created should have a name ending with the word Exception so there is never any question that the class is an exception class.

• Exceptions should be used to communicate exceptional conditions not for using simple validation
Don’t use them to communicate events that are expected, such as reaching the end of a file. Strong type checking and validation are powerful tools to prevent unexpected exceptions and to document and test code.

When to throw exception
• Never throw in the course of normal use
The use of the term exception in programming has to do with the thinking that an exception should represent an exceptional condition. Exceptional conditions, by their very nature, do not normally occur; don’t throw exceptions in normal cases.
Custom Exception
• Wrap that exception with additional information before re-throwing it
If code catches an exception that it isn’t going to handle, consider whether it should wrap that exception with additional information before re-throwing it.

General Guideline
• Easily understandable custom message
Display User-Friendly generic, harmless error message to the user and logged the Original exception information with context of execution the code

• Put a single catch (Exception ex) per thread
Generic exception handling should be done in a central point in your application. Each thread needs a separate try/catch block. When an application starts several threads to do some background processing, often creates a class for storing processing results. Add a field for storing an exception that could happen.

• Use one try and many catches
When placing exception-handling code in the applications, it’s generally better to enclose all code that may throw an exception in a single try block and have multiple catch blocks set to trap different expected exceptions. Having all catch statements in a central location increases the readability of the code.

• Order catch blocks from specific to general
When placing catch blocks in the code that is set to catch different types of exception, always place them in order from most specific to most general. Doing so not only makes it clear that specific exception types will be handled before the more general types, but it also helps other developers reading your code understand what’s going on.
Every exception that is defined within the .NET framework derives from a class called Exception. This class is used to describe a general error, whose specificity is not known. The catch block should be built up such a way which traps more specific exception towards generic. The order of exception is to allow trapping all possible errors and act intelligently according to the type of exception encountered.
For e.g. TCPStreamException -> SocketException -> Exception

• Generic Exceptions caught should be published
If a generic Exception is caught log it somewhere. But log it only once.

• Cleanup code should be put in finally blocks
Ideally, it’s no possible for not handling a lot of generic exceptions in a central exception handler; a lot more finally blocks than catch blocks. Never do cleanup code, e.g., closing streams, restoring state (as the mouse cursor), outside of a finally block.

• Use “using” everywhere
Simply calling Dispose() on an object is not enough. The using keyword will prevent resource leaks even on the presence of an exception.

• Avoid changing exceptions without adding semantic value
Only change an exception if you need to add some semantic value to it – e.g., you’re doing a DBMS connection driver, so the user doesn’t care about the specific socket error and wants only to know that the connection failed.
If you ever need to do it, please, keep the original exception on the InnerException member. Don’t forget that your exception handling code may have a bug too, and if you have InnerException, you may be able to find it easier.

• Exceptions should be marked [Serializable]
A lot of scenarios needs that exceptions are serializable. When deriving from another exception class, don’t forget to add that attribute otherwise it couldn’t be known when the method will be called from Remoting components or Web Services.

• Always ensure you reach a valid state
The minimum standard for exception handling should be to ensure that the object returns to a valid state after the exception occurs, and a caller should be able to safely assume that there were no side effects from an exception in a method call. Perform any needed cleanup to ensure this valid state in a finally block so that it always takes place.

• Throw the closest match
In situations where more than one exception can represent the same error, always throw the exception type that most closely matches the error condition. In the case of a division by zero error, for example, where either an ArithmeticException or a DivideByZero exception could apply, it should throw the latter instead of the former. The main idea is to always communicate the most specific information possible about a given error condition to the code that will catch the exception.
• Extend the ApplicationException, not the base Exception, class
When creating a custom exception, always extend the ApplicationException class, never the base System.Exception class. Doing so keeps user-defined exceptions in a separate object hierarchy than exceptions that could be thrown by the .NET runtime.

• Use the inner exception property when rethrowing
Sometimes, it is needed to create and throw a new exception of one type in response to catching an exception of another type in your code. In those cases, use one of the overloaded constructors of the base System.Exception class to wrap the exception you caught in the new exception you are throwing. The calling code can then examine the InnerException property of the exception thrown to it to determine the underlying cause of the problem.

• Each exception class should have at least the three original constructors

• Avoid keeping Try-Catch-Finally block in loop
This cost s more and bad practice of coding.
• Don’t trust external data
External data is not reliable. It must be extensively checked. It doesn’t matter if the data is coming from the registry, database, from a disk, from a socket, from a file you just wrote or from the keyboard. With the need external data, the following situations can be raised:
a)      Not enough security privileges
b)      The information is not there
c)      The information is incomplete
d)      The information is complete, but invalid

• Don’t throw new Exception
Exception is a too broad class, and it’s hard to catch without side-effects. Derive own exception class, but derive it from ApplicationException. Set a specialized exception handler for exceptions thrown by the framework and another for exceptions thrown by developer.

• Don’t put important exception information on the Message field
Exceptions are classes. When you return the exception information, create fields to store data.

• Don’t log Exception.Message! Log Exception.ToString()
Always log Exception.ToString() and never Exception.Message. Exception.ToString() gives you a stack trace, the inner exception and the message.
• Don’t catch (Exception) more than once per thread
There are rare exceptions (no pun intended) to this rule. If you need to catch an exception, always use the most specific exception for the code you’re writing.

• Don’t ever swallow exceptions
The worst thing you can do is catch (Exception) and put an empty code block on it. Never do this.

• Don’t return special values on error conditions
Exceptions makes the common case faster, because when returns special values from methods, each method return needs to be checked and this consumes at least one processor register more, leading to slower code. Special values can be ignored
Special values don’t carry stack traces, and rich error details.

• Don’t use exception handling as means of returning information from a method
This is a bad design. Not only exceptions are slow (as the name implies, they’re meant only to be used on exceptional cases), but a lot of try/catch blocks in the code makes the code harder to follow. Proper class design can accommodate common return values.

• Don’t clear the stack trace when re-throwing an exception
The stack trace is one of the most useful information that an exception carries.

• When in doubt, don’t Assert, throw an Exception
Don’t forget that Debug.Assert is removed from release code. When checking and doing validation, it’s often better to throw an Exception than to put an assertion in your code.
Know better / try to find out predefined exception first
• Don’t defining a new exception class if it is in predefined in System namespace
If there’s a good predefined exception in the System namespace that describes the exception condition-one and that will make sense to the users of the class-use that one rather than defining a new exception class and put specific information in the message.
Exception Policies
This is the strategy how the exceptions should be categorized and handled. It determines how a set of exception types are to be handled. Each and every policy contains one or more exception type.

Sample policies…

o       Exception of type ApplicationException should be logged.

o       Exception of the type SqlClientException should be caught and wrapped with an exception of the DataLayerException and re-throw.

o       Exception of the SecurityException should be caught and replace with an AccessDeniedException

Implementation of Structured Exceptions Handing as Enterprise Library

The exception management architecture of an application capable to

o Detect Exception
o Perform code clean up
o Wrap one exception inside another
o Replace one exception with another
o Logging and reporting error information
o Generating events that can be monitored externally to assist system operation
1. Construction of Email Notification Settings Class

2. Construction of Windows Event Log Settings Class

3. Construction of File Log Settings Class

4. Construction of Error Handler class which works with the parameters retrieving from the above classes

5. Implementation of Event handled in Application_Error event of global.asax => Applying the notification as on required

6. Formation of information along with the context of the application and other

7. Creating semantic exception messages/description for generating user-friendly message to be displayed locally or in the redirected error page.

More from MSDN – Important Links

.NET Framework Developer’s Guide
Best Practices for Handling Exceptions

.NET Architectural Guide
Exception Management Architecture Guide
Exceptions List

1)      System.OutOfMemoryException: Thrown when an attempt to allocate memory (via new) fails.

2)      System.StackOverflowException: Thrown when the execution stack is exhausted by having too many pending method calls; typically indicative of very deep or unbounded recursion.

3)      System.NullReferenceException: Thrown when a null reference is used in a way that causes the referenced object to be required.

4)      System.TypeInitializationException: Thrown when a static constructor throws an exception, and no catch clauses exists to catch in.

5)      System.InvalidCastException: Thrown when an explicit conversion from a base type or interface to a derived types fails at run time.

6)      System.ArrayTypeMismatchException: Thrown when a store into an array fails because the actual type of the stored element is incompatible with the actual type of the array.

7)      System.IndexOutOfRangeException: Thrown when an attempt to index an array via an index that is less than zero or outside the bounds of the array.

8)      System.MulticastNotSupportedException: Thrown when an attempt to combine two non-null delegates fails, because the delegate type does not have a void return type.

9)      System.ArithmeticException: A base class for exceptions that occur during arithmetic operations, such as DivideByZeroException and OverflowException.

10)  System.DivideByZeroException: Thrown when an attempt to divide an integral value by zero occurs.

11)  System.OverflowException: Thrown when an arithmetic operation in a checked context overflows.

12)  System.AppDomainUnloadedException: Thrown when attempting to use an unloaded application domain.

13)  System.ApplicationException: Thrown when a non-fatal application error has occurred.

14)  System.ArgumentException: Thrown when an argument passed is not valid.

15)  System.ArgumentNullException: Thrown when a null is passed as a method parameter that does not accept null values.

16)  System.ArgumentOutOfRangeException: Thrown when a passed value is outside the range of a methods parameter.

17)  System.ArithmeticException: Thrown when an error occurs while performing arithmetic and conversion operations.

18)  System.ArrayTypeMismatchException: Thrown when adding a value of the incorrect data type to an array.

19)  System.DivideByZeroException: Thrown whenever a value is divided by zero.

20)  System.DllNotFoundException Thrown when a DLL referenced as imported is not available.

21)  System.IndexOutOfRangeException: Thrown when trying to access an invalid index in an array.

22)  System.InvalidCaseException: Thrown when an invalid conversion attempt is made.

23)  System.NullReferenceException: Thrown when attempting to dereference a null object reference.

24)  System.OutOfMemoryException: Thrown when memory is not available to perform the specified task.

25)  System.OverflowException: Thrown when an operation overflow occurs.

26)  System.RankException: Thrown when an array with the wrong number of dimensions is passed to a methods parameter.

27)  System.SystemException: Is the base class for all exception classes in the System namespace.

28)  System.Data.ConstraintException: Thrown when a constraint is violated.

29)  System.Data.DataException: Thrown when an ADO.NET component generates an error.

30)  System.Data.DBConcurrencyException: Thrown when the number of rows affected in an update procedure is zero.

31)  System.Data. DeletedRowInaccessibleException: Thrown when attempting to perform data manipulation operations on a data row that has been deleted.

32)  System.Data. InvalidConstraintException: Thrown when a data relationship is violated.

33)  System.Data. NoNullAllowedException: Thrown when inserting a null value where one is not accepted.

34)  System.IO. DirectoryNotFoundException: Thrown when a specified directory cannot be found.

35)  System.IO.FileLoadException: Thrown when a file cannot be loaded.

36)  System.IO.IOException: Thrown when an I/O error occurs.

37)  System.IO.PathToLongException: Thrown when a path or file name are too long.

38)  System.Runtime.Remoting: Thrown when an error occurs during a remote RemotingException operation.

39)  System.Runtime.Remoting: RemotingTimeoutException Thrown when the response of a server or client exceed a predefined interval.

40)  System.Runtime.Remoting.ServerException: Thrown when an error occurs while working with a remote component that is an unmanaged application incapable of throwing an exception.

41)  System.Runtime.Serialization.SerializationException: Thrown when an error occurs during the serialization or deserialization of a component.

42)  System.Web.HttpException: Allow an http exception to be thrown.

43)  System.XML.XmlException: Provides exception information about the last XML exception.


under: 13732, 9536