Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

C# Exceptions:


In C#, an exception is an unexpected or abnormal condition that occurs during the execution of a program that disrupts the normal flow of the program's instructions. When an exception occurs, the runtime environment generates an object of a specific type (derived from the Exception class) to represent the exception, and the program can handle the exception using exception handling mechanisms.

Here's a simple explanation with an example:

Suppose we have a program that reads a number from the user and divides it by another number. However, if the user enters zero as the divisor, it will result in a division by zero exception.

Example

using System;

class Program
{
static void Main(string[] args)
{
try
{
Console.Write("Enter a number: ");
int number1 = int.Parse(Console.ReadLine());

Console.Write("Enter another number: ");
int number2 = int.Parse(Console.ReadLine());

int result = DivideNumbers(number1, number2);
Console.WriteLine("Result of division: " + result);
}
catch (FormatException)
{
Console.WriteLine("Invalid input. Please enter a valid number.");
}
catch (DivideByZeroException)
{
Console.WriteLine("Error: Division by zero is not allowed.");
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}

static int DivideNumbers(int dividend, int divisor)
{
return dividend / divisor;
}
}

In this example:

Exception handling allows the program to gracefully handle unexpected errors and prevent the program from crashing. It provides a way to recover from errors, log diagnostic information, and guide users on how to resolve the issue.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java