An exception is defined as an event that occurs during the execution of a program that is unexpected by the program code. The actions to be performed in case of occurrence of an exception is not known to the program. In such a case, we create an exception object and call the exception handler code. The execution of an exception handler so that the program code does not crash is called exception handling. Exception handling is important because it gracefully handles an unwanted event, an exception so that the program code still makes sense to the user.
Keyword |
Definition |
try |
Used to define a try block. This block holds the code that may throw an exception. |
catch |
Used to define a catch block. This block catches the exception thrown by the try block. |
finally |
Used to define the finally block. This block holds the default code. |
throw |
Used to throw an exception manually. |
Let us take a simple example to understand what an exception is:
csharp
using System;
class GFG {
static void Main( string [] args)
{
int [] arr = { 1, 2, 3, 4, 5 };
for ( int i = 0; i < arr.Length; i++) {
Console.WriteLine(arr[i]);
}
Console.WriteLine(arr[7]);
}
}
|
Runtime Error:
Unhandled Exception:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at GFG.Main (System.String[] args) [0x0002e] in <9fa39b3b4dec49eb8af89dc70d5a0618>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at GFG.Main (System.String[] args) [0x0002e] in <9fa39b3b4dec49eb8af89dc70d5a0618>:0
Output:
1
2
3
4
5
In the code given above, the array named ‘arr’ is defined for 5 elements, indices 0 to 4. When we try to access the 7th element of the array, that is non-existent, program code throws an exception and the above message is displayed. The exception can be handled using the System.Exception class of C#. This will be depicted in the code given below.
Exception Handling Using try-catch block
The code given below shows how we can handle exceptions using the try-catch block. The code that may generate an exception is placed inside the try block. In this case, the access to the 7th element is put inside the try block. When that statement is executed an exception is generated, which is caught by the catch block. The object of the type IndexOutOfRangeException is used to display a message to the user about the exception that has occurred.
Syntax:
try
{
// statements that may cause an exception
}
catch( Exception obj)
{
// handler code
}
csharp
using System;
class Program : System.Exception {
static void Main( string [] args)
{
int [] arr = { 1, 2, 3, 4, 5 };
for ( int i = 0; i < arr.Length; i++) {
Console.WriteLine(arr[i]);
}
try {
Console.WriteLine(arr[7]);
}
catch (IndexOutOfRangeException e) {
Console.WriteLine( "An Exception has occurred : {0}" , e.Message);
}
}
}
|
Output:
1
2
3
4
5
An Exception has occurred : Index was outside the bounds of the array.
Using Multiple try-catch blocks
In the code given below, we attempt to generate an exception in the try block and catch it in one of the multiple catch blocks. Multiple catch blocks are used when we are not sure about the exception type that may be generated, so we write different blocks to tackle any type of exception that is encountered.
The finally block is the part of the code that has to be executed irrespective of if the exception was generated or not. In the program given below the elements of the array are displayed in the finally block.
Syntax:
try
{
// statements that may cause an exception
}
catch(Specific_Exception_type obj)
{
// handler code
}
catch(Specific_Exception_type obj)
{
// handler code
}
.
.
.
finally
{
//default code
}
csharp
using System;
class Program {
static void Main( string [] args)
{
int [] arr = {19, 0, 75, 52};
try {
for ( int i = 0; i < arr.Length; i++) {
Console.WriteLine(arr[i] / arr[i + 1]);
}
}
catch (IndexOutOfRangeException e) {
Console.WriteLine( "An Exception has occurred : {0}" , e.Message);
}
catch (DivideByZeroException e) {
Console.WriteLine( "An Exception has occurred : {0}" , e.Message);
}
catch (ArgumentOutOfRangeException e) {
Console.WriteLine( "An Exception has occurred : {0}" , e.Message);
}
finally {
for ( int i = 0; i < arr.Length; i++) {
Console.Write( " {0}" , arr[i]);
}
}
}
}
|
Output:
An Exception has occurred : Attempted to divide by zero.
19 0 75 52
User Defined Exceptions
User-defined exceptions are useful when we want to code an exception that may not be defined by the language. For example, in a boiler room, if the temperature rises above some threshold then the heat must be turned off. For understanding how user-defined exceptions are used we take an example of a division by zero. Here we define a class DivByZero that inherits from Exception and is called by the DivisionOperation function when the denominator is equal to zero. Since the call for the function is may or may not throw an exception it is placed in the try block. A catch block is defined to catch any exception of type Exception and the Message property prints the type of exception that has occurred.
csharp
using System;
class DivByZero : Exception {
public DivByZero()
{
Console.Write( "Exception has occurred : " );
}
}
class Program {
public double DivisionOperation( double numerator,
double denominator)
{
if (denominator == 0)
throw new DivByZero();
return numerator / denominator;
}
static void Main( string [] args)
{
Program obj = new Program();
double num = 9, den = 0, quotient;
try {
quotient = obj.DivisionOperation(num, den);
Console.WriteLine( "Quotient = {0}" , quotient);
}
catch (Exception e) {
Console.Write(e.Message);
}
}
}
|
Output:
Exception has occurred : Exception of type 'DivByZero' was thrown.
Similar Reads
C# Exceptions
An exception in C# is an unwanted or unexpected event that occurs at runtime. It affects the normal flow of the program. Common exceptions include invalid input, divide-by-zero operations, or accessing invalid array indices. C# provides a powerful exception-handling mechanism to successfully recover
4 min read
C# | Array IndexOutofRange Exception
C# supports the creation and manipulation of arrays, as a data structure. The index of an array is an integer value that has value in the interval [0, n-1], where n is the size of the array. If a request for a negative or an index greater than or equal to the size of the array is made, then the C# t
3 min read
Console.ReadLine() Method in C#
This method is used to read the next line of characters from the standard input stream. It comes under the Console class(System Namespace). If the standard input device is the keyboard, the ReadLine method blocks until the user presses the Enter key. And if standard input is redirected to a file, th
2 min read
LINQ | Set Operator | Except
In LINQ, Set operators are those operators in query expression which return a result set based on the existence or non-existence of the equivalent elements within the same or different collections or sequences or sets. The standard query operator contains the following set operators: Union Intersect
3 min read
File.ReadAllText(String) Method in C# with Examples
File.ReadAllText(String) is an inbuilt File class method that is used to open a text file then reads all the text in the file and then closes the file.Syntax:Â Â public static string ReadAllText (string path); Parameter: This function accepts a parameter which is illustrated below:Â Â path: This is th
2 min read
UInt32.Parse(String) Method in C# with Examples
UInt32.Parse(String) Method is used to convert the string representation of a number to its 32-bit unsigned integer equivalent. Syntax: public static uint Parse (string str); Here, str is a string containing a number to convert. The format of str will be [optional white space][optional sign]digits[o
2 min read
File.ReadAllLines(String) Method in C# with Examples
File.ReadAllLines(String) is an inbuilt File class method that is used to open a text file then reads all lines of the file into a string array and then closes the file.Syntax:Â Â public static string[] ReadAllLines (string path); Parameter: This function accepts a parameter which is illustrated belo
2 min read
UInt16.Parse(String) Method in C# with Examples
UInt16.Parse(String) Method is used to convert the string representation of a number to its 16-bit unsigned integer equivalent. Syntax: public static ushort Parse (string str); Here, str is a string containing a number to convert. The format of str will be [optional white space][optional sign]digits
2 min read
Null-Coalescing Operator in C#
In C#, ?? operator is known as Null-coalescing operator. It will return the value of its left-hand operand if it is not null. If it is null, then it will evaluate the right-hand operand and returns its result. Or if the left-hand operand evaluates to non-null, then it does not evaluate its right-han
4 min read
Int32.Parse(String) Method in C# with Examples
Int32.Parse(String) Method is used to convert the string representation of a number to its 32-bit signed integer equivalent. Syntax: public static int Parse (string str); Here, str is a string that contains a number to convert. The format of str will be [optional white space][optional sign]digits[op
2 min read