- You can throw exceptions to indicate error conditions:
- An exception is an object that describes the error.
- All exception classes inherit from System.Exception.
- To throw an exception:
- In Visual C#, use the throw keyword.
- To catch an exception:
- In Visual C#, define try, catch, and finally blocks
Applications must be able to handle errors and exceptions in a uniform way. The CLR greatly assists the design of error-tolerant software by providing a platform that you can use to notify applications of errors in a consistent way. All .NET Framework methods indicate failure by throwing exceptions. An application can throw an exception when it encounters a condition outside its control. When the application throws an exception, the CLR searches the call tree for a catch handler that can handle that type of exception.
To throw an exception, use the throw (C#) keyword, followed by the exception object that you want to throw. The .NET Framework contains a large number of predefined exception classes that represent a wide range of common exceptions.
The following example:
static void Main(string args)
Console.WriteLine("Enter first number");
int i = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter second number");
int j = Convert.ToInt32(Console.ReadLine());
int k = i / j;
catch (Exception ex)
Output is display below:
Note: - The try block contains code that may throw an exception. When an exception is thrown in this block, the first catch block whose filter matches the class of the exception catches it. Note that the filter is specified as part of the catch clause.
• The catch block catches exceptions of a particular type. The exception object provides information about the error; for example, all exception objects have a Message property that describes the error.
• The finally block always executes regardless of whether an exception is thrown. The finally block performs clean-up operations such as closing database connections or closing windows.