EXCEPTION HANDLING

Exceptions Handling

Handling Errors during the Program Execution



Table of Contents


1.What are Exceptions?

2.Handling Exceptions

3.The System.Exception Class

4.Types of Exceptions and their Hierarchy

5.Raising (Throwing) Exceptions

What are Exceptions?


  • The exceptions in .NET Framework are classic implementation of the OOP exception model.
  • Deliver powerful mechanism for centralized handling of errors and unusual events.
  • Substitute procedure-oriented approach, in which each function returns errorcode.
  • Simplify code construction and maintenance.
  • Allow the problematic situations to be processed at multiple levels.

Handling Exceptions

In C# the exceptions can be handled by the try-catch-finally construction. 

EXAMPLE:

try
{
//Do some work that can raise an exception
}
catch(SomeException)
{
//Handle the caught exception
}


Catch blocks can be used multiple times to process different exception types



EXCEPTION HANDLING EXAMPLE :


The System.Exception Class

  • Exceptions in .NET are objects
  • The System.Exception class is base for all exceptions in 
    • CLR Contains information for the cause of the error or the unusual situation
      • Message – text description of the exception
      • StackTrace – the snapshot of the stack at the moment of exception throwing
      • InnerException – exception caused the current exception (if any)


Exception Hierarchy

Exceptions in .NET Framework are organized in a hierarchy

Types of Exception


All .NET exceptions inherit from System.Exception.
The system exceptions inherit from System.SystemException, e.g.
  • System.ArgumentException
  • System.NullReferenceException
  • System.OutOfMemoryException
  • System.StackOverflowException
User-defined exceptions should inherit from System.ApplicationException

Throwing Exceptions


  • Exceptions are thrown (raised) by throw keyword in C#
  • When an exception is thrown:
    • The program execution stops.
    • The exception travels over the stack until a suitable catch block is reached to handle it.
    • Unhandled exceptions display error message.

Using the "Throw" Keyword

  • Throwing an exception with error message:
                            throw new ArithmeticException("Invalid Amount!");
  • Exceptions can take message and cause:
try
{
  Int32.Parse(str);
}
catch (FormatException fe)
{
  throw new ArgumentException("Invalid number", fe);
}


No comments:

Post a Comment