Exception in .NET


What is an Exception in .NET?

Exceptions are errors that occur during the runtime of a program.
The advantage of using exceptions is that the program doesn’t terminate due to the occurrence of the exception.
Whenever an exception is occurred the .NET runtime throws an object of specified type of Exception.
The class ‘Exception’ is the base class of all the exceptions.
Here are a few common types of exceptions:
  • ArgumentException
  • ArgumentNullException
  • ArgumentOutOfRangeException
  • DuplicateWaitObjectException
  • ArithmeticException
  • DivideByZeroException
  • OverflowException
  • NotFiniteNumberException
  • ArrayTypeMismatchException
  • ExecutionEngineException
  • FormatException
  • IndexOutOfRangeException
  • InvalidCastException
  • InvalidOperationException
  • ObjectDisposedException
  • InvalidProgramException
  • IOIOException
  • IODirectoryNotFoundException
  • IOEndOfStreamException
  • IOFileLoadException
  • IOFileNotFoundException
  • IOPathTooLongException
  • NotImplementedException
  • NotSupportedException
  • NullReferenceException
  • OutOfMemoryException
  • RankException
  • SecuritySecurityException
  • SecurityVerificationException
  • StackOverflowException
  • ThreadingSynchronizationLockException
  • ThreadingThreadAbortException
  • ThreadingThreadStateException
  • TypeInitializationException
  • UnauthorizedAccessException
It is a runtime error which occurs because of unexpected and invalid code execution.
.Net had enhanced exception handling features. All exceptions inherit from System.Exception.

Explain how to Handle Exceptions in .NET 2.0.

The different methods of handling the exceptions are:
  • 1.
    try
    {
         // code
    }
    catch(Exceptiontype *etype_object)
    {
         // code
    }
  • 2.
    try
    {
           // code
    }
    catch(Exceptiontype *etype_object)
    {
            throw new Custom_Exception();
    }
Exceptions should never be handled by catching the general System.Exception errors, rather specific exceptions should be caught and handled.
They are handled using try catch and finally. Finally is used to cleanup code as it's always executed irrespective of whether an exception has occurred or not. E.g.
try
{
      FileInfo file=new FileInfo(@"c:\abc.txt")
}
catch(FileNotFoundException e)
{
      //handle exception
}
Finally
{
         //cleanup code here
}
If file is found, then finally will get invoked else both catch and finally will occur.

What are Custom Exceptions?

Custom Exceptions are user defined exceptions.
There are exceptions other than the predefined ones which need to be taken care of.
For example: The rules for the minimum balance in a Salary A/C would be different from that in a Savings A/C due to which these things need to be taken care of during the implementation.
Custom exception needs to derive from the System.Exception class. You can either derive directly from it or use an intermediate exception like SystemException or ApplicationException as base class. Custom exeptions are created to handle very specific exceptions and to provide more details about it.
We need custom exceptions to have better predictability of our application. By using custom exceptions we can throw and handle our own exceptions, providing a much more predictable and stable application.
public class MyCustomException : Exception
{
        public MyCustomException()
        : base()
        {
        }

        public MyCustomException(string Message)
        : base(Message)
        {
        }
        public MyCustomException(string Message, Exception InnerException)
        : base(Message, InnerException)
        {
        }
        protected MyCustomException(SerializationInfo Info, StreamingContext Context)
        : base(Info, Context)       
        {
        }
}

Implementing a Web Service in .NET:

The following code sample is to Implement a Web Service in .NET:

Following is a VBScript example
"WebMethod()" converts the functions in your application into web services
Example:
<%@ WebService Language="VBScript" Class="KmToMConvert" %>
Imports System
Imports System.Web.Services
Public Class KmToMConvert :Inherits WebService
   <WebMethod()> Public Function KilometerToMeter(ByVal Kilometer As String) As String
         return (Kilometer * 1000)
         end function
end class
[WebService(Namespace = http://tempuri.org/)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
     [WebMethod]
     public string HelloWorld()
     {
            return "Hello World";
     }
}

ViewState in Asp.net


Viewstate: 

         Viewstate is used to maintain or retain values on postback. It helps in preserving a page. It is internally maintained as a hidden field in encrypted form along with a key.

  • If a site happens to not maintain a ViewState, then if a user has entered some information in a large form with many input fields and the page is refreshes, then the values filled up in the form are lost.
  • The same situation can also occur on submitting the form. If the validations return an error, the user has to refill the form.
  • Thus, submitting a form clears up all form values as the site does not maintain any state called ViewState.
  • In ASP .NET, the ViewState of a form is maintained with a built-in state management technique keeps the state of the controls during subsequent postbacks by a particular user.
  • The ViewState indicates the status of the page when submitted to the server. The status is defined through a hidden field placed on each page with a <form runat="server"> control.
    <input type="hidden" name="__VIEWSTATE" value="CareerRide">
  • The ViewState option can be disabled by including the directive <%@ Page EnableViewState="false"%> at the top of an .aspx page
  • If a ViewState of a certain control has to be disabled, then set EnableViewState="false".
 
Advantages:
i) No server resources.
ii) Viewstate ensures security because it stores the data in encrypted format.
iii) Viewstates are simple. They are used by enabling or disabling the viewstate properties.
iv) It is based on the wish of developer that they want to implement it at the page level or at control level.

Disadvantages:
i) If large amount of data is stored on the page, then page load might cause a problem.
ii) Does not track across pages. Viewstate information does not automatically transfer from page to page.