An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: try, catch, finally, and throw.
Assuming a block raises an exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following −
try { // statements causing exception } catch( ExceptionName e1 ) { // error handling code } catch( ExceptionName e2 ) { // error handling code } catch( ExceptionName eN ) { // error handling code } finally { // statements to be executed }
You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one exception in different situations.
Let us see an example of what exception is and how it will be handled using try-catch block.
// C# program to show how // Exceptions occur in a program using System; class Interviewbit { static void Main(string[] args){ // Declare an array of max index 4 int[] arr = { 1, 2, 3, 4, 5 }; // Display values of array elements for (int i = 0; i < arr.Length; i++) { Console.WriteLine(arr[i]); } // Try to access invalid index of array Console.WriteLine(arr[7]); // An execption is thrown upon executing // the above line } }
The above code will give following output and 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 Interviewbit.Main (System.String[] args) [0x0002e] in <9fa39b3b4dec49eb8af89dc70d5a0618>:0
Output:
1 2 3 4 5
Explaination:
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.
We handle such exceptions using try-catch block as shown in below code-
// Exception handling of above code // using try catch blocks using System; class Interviewbit: System.Exception { static void Main(string[] args) { // Declare an array of max index 4 int[] arr = { 1, 2, 3, 4, 5 }; // Display values of array elements for (int i = 0; i < arr.Length; i++) { Console.WriteLine(arr[i]); } try { // Try to access invalid index of array Console.WriteLine(arr[7]); // An execption is thrown upon executing // the above line } catch (IndexOutOfRangeException e) { // The Message property of the object // of type IndexOutOfRangeException // is used to display the type of exception // that has occurred to the user. 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.
You can also define your own exception. User-defined exception classes are derived from the Exception class. The following example demonstrates this −
using System; namespace UserDefinedException { class TestTemperature { static void Main(string[] args) { Temperature temp = new Temperature(); try { temp.showTemp(); } catch(TempIsZeroException e) { Console.WriteLine("TempIsZeroException: {0}", e.Message); } Console.ReadKey(); } } } public class TempIsZeroException: Exception { public TempIsZeroException(string message): base(message) { } } public class Temperature { int temperature = 0; public void showTemp() { if(temperature == 0) { throw (new TempIsZeroException("Zero Temperature found")); } else { Console.WriteLine("Temperature: {0}", temperature); } } }
When the above code is compiled and executed, it produces the following result −
TempIsZeroException: Zero Temperature found
Try the following example in the editor below.
You are given a function named division which throw an exception if the value of divisor is 0 as shown below. Your task is to complete the main function and use try and catch blocks. In try block call and print the value return by division function, else if an exception is thrown print the exception in catch.