Home > DeveloperSection > Blogs > Exception Class in C#

Exception Class in C#


C# C# 
Ratings:
0 Comment(s)
 1464  View(s)
Rate this:

Exception Class in C#

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: -

1.  using System;

2.  class ExceptionClass

3.  {

4.  public static void Main()

5.  {

6.  int x = 0;

7.  try

8.  {

9.  int y = 100 / x;

10. }

11. catch (ArithmeticException e)

12. {

13. Console.WriteLine("ArithmeticException Handler: {0}", e.ToString());

14. }

15. catch (Exception e)

16. {

17. Console.WriteLine("Generic Exception Handler: {0}", e.ToString());

18. }

19. Console.ReadKey();

20. }

21. }

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: -


Don't want to miss updates? Please click the below button!

Follow MindStick