Practice
Resources
Contests
Online IDE
New
Free Mock
Events New Scaler
Practice
Improve your coding skills with our resources
Contests
Compete in popular contests with top coders
logo
Events
Attend free live masterclass hosted by top tech professionals
New
Scaler
Explore Offerings by SCALER

Exception Handling in C#

C# - Exception Handling

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.

  • try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks.
  • catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
  • finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
  • throw − A program throws an exception when a problem shows up. This is done using a throw keyword.

 

Syntax

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.

Creating User-Defined Exceptions

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.

Start solving Exception Handling in C# on Interview Code Editor
Hints
  • Complete Solution

Discussion


Loading...
Click here to start solving coding interview questions
Free Mock Assessment
Fill up the details for personalised experience.
Phone Number *
OTP will be sent to this number for verification
+1 *
+1
Change Number
Graduation Year *
Graduation Year *
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
*Enter the expected year of graduation if you're student
Current Employer
Company Name
College you graduated from
College/University Name
Job Title
Job Title
Engineering Leadership
Software Development Engineer (Backend)
Software Development Engineer (Frontend)
Software Development Engineer (Full Stack)
Data Scientist
Android Engineer
iOS Engineer
Devops Engineer
Support Engineer
Research Engineer
Engineering Intern
QA Engineer
Co-founder
SDET
Product Manager
Product Designer
Backend Architect
Program Manager
Release Engineer
Security Leadership
Database Administrator
Data Analyst
Data Engineer
Non Coder
Other
Please verify your phone number
Edit
Resend OTP
By clicking on Start Test, I agree to be contacted by Scaler in the future.
Already have an account? Log in
Free Mock Assessment
Instructions from Interviewbit
Start Test