Explain about the Exception handing in C# with example?
Explain about the Exception handing in C# with example?
2 Answers
Exception handling is a way to gracefully handle runtime errors in a C# program. When an error occurs during the execution of a program, an exception is thrown, which can be caught and handled in a try-catch block. Here's an example:
try
{
// Code that may throw an exception
int x = 10 / 0; // This will throw a divide by zero exception
}
catch (DivideByZeroException ex)
{
// Handle the exception
Console.WriteLine("An error occurred: " + ex.Message);
}
finally
{
// Code that will always execute, regardless of whether an exception was thrown or not
Console.WriteLine("The program has finished executing.");
}
In this example, we have a try-catch-finally block. The code inside the try block attempts to divide the number 10 by zero, which is an illegal operation and will throw a DivideByZeroException.
When the exception is thrown, the catch block catches it and executes its code. In this case, we simply print an error message that includes the exception message.
The finally block is optional and will always execute, regardless of whether an exception was thrown or not. In this example, we print a message that indicates the program has finished executing.
There are other types of exceptions that can be caught, such as ArgumentException, ArgumentNullException, IndexOutOfRangeException, and so on. It's important to catch only the specific exceptions that you expect might be thrown and to handle them appropriately.
In addition to try-catch-finally blocks, C# also provides the throw statement, which allows you to manually throw an exception. This can be useful when you want to create a custom exception that isn't already provided by the .NET Framework.
if (x < 0)
{
throw new ArgumentException("x must be a positive integer.");
}
In this example, we use the throw statement to manually throw an ArgumentException if the variable x is less than zero. We pass a string message to the constructor of the ArgumentException, which will be displayed when the exception is caught and handled.
- Try - The code in which the exception is likely to occur is placed in the try block.
- Catch - Exception is caught in this block. The catch keyword is used to catch it.
- Finally - finally block is used so that whether the exception comes or not the code has to be executed! For example, if you open a file to read or write, then it is also necessary to close that file. That's why we use finally block for this work.
- Throw - A program throws an exception when there is a problem in that program. For this throw keyword is used.
try {
// If such codes are kept in this block, then there is a possibility of an exception coming.
}
catch( Exception-class e1 )
{
// exception is caught in this block
}
finally
{
// In this block the code is kept which has to be executed
}
- System.ApplicationException - The System.ApplicationException class supports exceptions that are generated from the application program.
- System.SystemException - System.SystemException class is the base class of all predefined exceptions in the System.
using System;
namespace ExceptionHandling {
class DivisionofNumber {
int res = 0 ;
public void division(int num1, int num2) {
try {
res = num1 / num2;
}
catch (DivideByZeroException e)
{
Console.WriteLine('Exception is : {0}',e);
}
finally
{
Console.WriteLine('Result is : {0}',res);
res = 0;
}
}
public static void Main() {
DivisionofNumber divObj = new DivisionofNumber();
divObj.division(25, 2); // no exception arise
divObj.division(25, 0); // exception arise
Console.ReadKey();
}
}
}
Result is: 12 Exception is: System.DivideByZeroException: Attempted to divide by zero. at DivisionofNumber.division(Int32 num1, Int32 num2) Result is : 0