In this blog I am trying to explain the concept of the Exception in C#.

Exception Class

Exception Class is the base class for all exceptions. When an error occurs, either the system or the currently executing application reports it by throwing an exception containing information about the error. Once thrown, an exception is handled by the application or by the default exception handler.

Try-Catch Blocks

The common language runtime (CLR) provides an exception handling model that is based on the representation of exceptions as objects, and the separation of program code and exception handling code into try blocks and catch blocks, respectively. There can be one or more catch blocks, each designed to handle a particular type of exception, or one block designed to catch a more specific exception than another block.

If an application handles exceptions that occur during the execution of a block of application code, the code must be placed within a try statement. Application code within a try statement is a try block. Application code that handles exceptions thrown by a try block is placed within a catch statement, and is called a catch block. Zero or more catch blocks are associated with a try block, and each catch block includes a type filter that determines the types of exceptions it handles.

Example: -
 using System;
 class ExceptionClass
 public static void Main()
 int x = 0;
 int y = 100 / x;
 catch (ArithmeticException e)
 Console.WriteLine("ArithmeticException Handler: {0}", e.ToString());
 catch (Exception e)
 Console.WriteLine("Generic Exception Handler: {0}", e.ToString());
Code Description: -

1.       Using System (include the System namespace).

2.       Create ExceptionClass class.

4.       Create Main method.

5.       Declare x named variable.

7.       Start try block.

9.  Write the statement in try block.

11.   Start catch block.

13.   Write the message on console from e variable.

And below code work same as 11 and 13 statement.

Output: -

  Modified On Sep-18-2014 01:24:14 PM

Leave Comment