Exceptions Handling in C# - Error handling in c# with example

Exceptions Handling in C# - Error handling in c# with example

13 Aug 2024
Advanced
148K Views
8 min read
Learn via Video Course & by Doing Hands-on Labs

Free C# Course Online

Exception Handling in C#: An Overview

Errors refer to the mistakes or faults that occur during program development or execution. If you don't find them and correct them, they cause a program to produce wrong results. In this C# Tutorial, we will explore more about Errors and Exceptions which will include exception handling in c#, types of errors in c#, try-catch-finally blocks in c#,and last proper use of try-catch, and finally block.

Types of Error Handling in C#

In programming language, errors can be divided into three categories as given below-

1. Syntax Errors

Syntax errors occur during development when you make type mistakes in code. For example, instead of writing while you write WHILE then it will be a syntax error since C# is a case-sensitive language.

    1.  bool flag=true;
      
      WHILE (flag) //syntax error, since c# is case sensitive
      {
       //TO DO:
      }

    2. Runtime Errors (Exceptions)

    Runtime errors, also called exceptions, occur during the program's execution and can be caused by improper user inputs, improper design logic, or system errors.

      1.  int a = 5, b = 0;
        int result = a / b; // DivideByZeroException
        
      2. Exceptions can be handled by using try-catch blocks.

      3. Logical Errors

      Logic errors occur when the program is written fine but does not produce the desired result. Logic errors are difficult to find because you need to know for sure that the result is wrong

          1. int a = 5, b = 6; double avg = a + b / 2.0; // logical error, it should be (a + b) / 2.0

        Read More - C# Programming Interview Questions

        Exception Handling In C#

        Exception handling is a mechanism for detecting and handling run-time errors. It is achieved by using the Try-Catch-Finally blocks and the throw keyword.

        1. Try block

        The try block encloses the statements that might throw an exception.

          1.  try
            {
             // Statements that can cause exception.
            }
             

          2. Catch block

          1. Catch block handles any exception if one exists.

             catch(ExceptionType e)
            {
             // Statements to handle exception.
            }

          3. Finally, block

            1. The finally block can be used for doing any clean-up process like releasing unused resources even if an exception is thrown. For example, disposing database connection.

               finally
              {
               // Statement to clean up.
              }

            4. Throw keyword

              1. This keyword is used to throw an exception explicitly.

                 catch (Exception e)
                {
                 throw (e);
                }  

              Key points about exception handling

              1. Exceptions are types that all directly or indirectly derive from the System. Exception class.

              2. Exception objects contain detailed information about the error, such as the state of the call stack and a text description of the error.

              3. A try block is used to throw multiple exceptions that can be handled by using multiple catch blocks.

              4. A more specialized catch block should be executed before a generalized one. Otherwise, the specialized catch block will never be executed.

              5. Exceptions can be explicitly generated by a program by using the throw keyword.

              6. If no exception-handling mechanism is used, the program stops executing with an error message.

              7. By providing a catch block without brackets or arguments, we can catch all exceptions that occur inside a try block.

                 Catch
                {
                 Console.WriteLine("oException" );
                } 
              8. By providing a catch block with an exception object, you can obtain more information about the type of exception that occurred.

                 catch(Exception e)
                {
                 Console.WriteLine(e.Message);
                }
                
              9. The statements inside the finally block are always executed whether an exception occurs or not in the program.

              10. Also, before the termination of the program finally block is always executed.

              Order of Try-Catch-Finally blocks

              In the order of exception handling, blocks try block comes first, after that, catch block(s) comes, and the last final block comes. Let's see in C# Compiler.

               try
              {
               // statements that can cause exception.
              }
              catch (MoreSpecificExceptionType e1)
              {
               // error handling code
              }
              catch (SpecificExceptionType e2)
              {
               // error handling code
              }
              catch (GeneralExceptionType eN)
              {
               // error handling code
              }
              finally
              {
               // statement to clean up.
              } 
              

              You can also skip finally block if required.

               try
              {
               // statements that can cause exception.
              }
              catch (MoreSpecificExceptionType e1)
              {
               // error handling code
              }
              catch (SpecificExceptionType e2)
              {
               // error handling code
              }
              catch (GeneralExceptionType eN)
              {
               // error handling code
              } 
                

              You can also skip catch block(s) if required.

               try
              {
               // statements that can cause exception.
              }
              finally
              {
               // statement to clean up.
              }
              

              Hence, a combination of try-catch-finally or try-catch or try-finally blocks is valid.

              List of C# Exceptions :

              List of C# Exceptions
              Conclusion

              I hope you will enjoy handling exceptions in C# while programming. I would like feedback from my blog readers. Your valuable feedback, questions, or comments about this article are always welcome. Also, Consider our C# Programming Course for a better understanding of all C# concepts.

              FAQs

              Q1. What are the 4 keywords of exception handling in C#?

              C# exception handling is built upon four keywords: try, catch, finally, and throw.

              Q2. What is error and exception handling?

              An error is an issue in a program that prevents the program from completing its task. In comparison, an exception is a condition that interrupts the normal flow of the program

              Q3. How to throw exception with error code in C#?

              Using the C# throw or the Visual Basic Throw statement. 

              Q4. What is error in C#?

              coding errors made by the programmer, errors due to wrong input, or other unforeseeable things

              Take our Csharp skill challenge to evaluate yourself!

              In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

              GET FREE CHALLENGE

              Share Article

              Live Classes Schedule

              Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
              Azure Developer Certification TrainingSep 14SAT, SUN
              Filling Fast
              10:00AM to 12:00PM (IST)
              Get Details
              ASP.NET Core Certification TrainingSep 15SAT, SUN
              Filling Fast
              09:30AM to 11:30AM (IST)
              Get Details
              Advanced Full-Stack .NET Developer Certification TrainingSep 15SAT, SUN
              Filling Fast
              09:30AM to 11:30AM (IST)
              Get Details
              .NET Solution Architect Certification TrainingSep 22SAT, SUN
              Filling Fast
              07:00AM to 09:00AM (IST)
              Get Details
              Software Architecture and Design TrainingSep 22SAT, SUN
              Filling Fast
              07:00AM to 09:00AM (IST)
              Get Details
              Advanced Full-Stack .NET Developer Certification TrainingSep 29SAT, SUN
              Filling Fast
              08:30PM to 10:30PM (IST)
              Get Details
              ASP.NET Core Certification TrainingSep 29SAT, SUN
              Filling Fast
              08:30PM to 10:30PM (IST)
              Get Details

              Can't find convenient schedule? Let us know

              About Author
              Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

              Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
              Accept cookies & close this