How Does Exception Handling Work in C#?

Exception handling is a built-in mechanism in .NET frameworks to detect and handle run-time errors. The .NET frameworks contain many standard exceptions. The exceptions are anomalies that occur during the execution of the program or in another aspect at the time of running the program. They can be because of user, logic, or system errors. If a user (programmer) does not provide a mechanism to handle these anomalies, the .NET runtime environment provides a default mechanism that terminates the program execution.

How Does Exception Handling Work in C#?

Exception: An Exception is an error that arises at the time of program execution. Exceptions do not occur at the time of compilation. Instead, they always occur at runtime and the user does not know in advance that what can be the exception. A number of Exceptions occur due to programmer logic errors or system errors. Like for example, divide by zero occurs an AirthmaticException.

C# provides four keywords for exception handling: try, catch, finally and throw.

Try: try block contains the code in which the exception can occur. The programmers write their own code, logic inside the try block to handle the different exceptions. One try block followed by many catch block.

Important Keywords to Consider

Catch, Finally, Throw - Important keywords for C#

Catch(): Catch block is used to catch the exception which occurs in the try block. At one time only one catch block executes.

Finally: ‘Finally’ always executes no matter the exception is thrown or not in the program. It’s always executed.

throw: The throw keyword is used to throw an exception in the program.

Example :
 //C#: Exception Handling: Multiple catch
 using System;
 class MyClient
 {
 public static void Main()
 {
 int x = 0;
 int div = 0;
 try
 {
 div = 100/x;
 Console.WriteLine("Not executed line");
 }
 catch(DivideByZeroException de)
 {
 Console.WriteLine("DivideByZeroException" );
 }
 catch(Exception ee)
 {
 Console.WriteLine("Exception" );
 }
 finally
 {
 Console.WriteLine("Finally Block");
 }
 Console.WriteLine("Result is {0}",div);
 } // end of the main function
 } // end of the main class

Handling Exception Throw Try, Catch and Finally, block

C# provides the three keywords to try to catch and to do exception handling. The try block encloses the statements that might throw an exception whereas the catch handles an exception if one exists. The finally block always executes in the program.

In C#, the exceptions can be handled by the try-catch-finally construction

The following syntax shows the use of the try, catch and finally block in c#:
 Try
 {
 the statement which can cause an exception.
 }
 catch(Type x)
 {
 statements for handling the exception.
 }
 Finally
 {
 any cleanup code.
 }

If any exceptions occur inside the try block, then the control transfers to the appropriate catch blocks or a finally block or with both catch and finally block.
If there is no exception occurs inside the try block then the control transfers to the finally block. We can say that the statements inside the final block are always executed. Note that it is an error to transfer control out of a finally block by using the break, continue, return, or goto statement.

It is an error to transfer control out of a finally block by using the break, continue, return, or goto statement.

In C#, exceptions are nothing but runtime Exceptions. The Exceptions is the ultimate base class for any Exception in the C#. The C# provides many runtime exceptions like as Arithmetic exception, indexOutOfBound exception, Stack Empty Exception, etc. In C# the programmers can create their own Exception classes, functions, etc, this should inherit from either the Exception classes or one of the standard derived classes of the Exception, class like DivideByZeroException or ArgumentException, and so on.

Example:

C#: Exception Handling

using system;
 class simple
 {
 public static void main()
 {
 int x=o;
 int div=0;
 try
 {
 div=100/x;
 console.writeLine("This line is not executed");
 }
 catch(DivideByZeroException de)
 {
 Console.writeLine("Exception Occured");
 }
 Console.writeLine("Result is{0}",div);
 }
 }

Throwing An Exception

Throwing An Exception

Throwing an Exception: In C#, it is possible to throw an exception programmatically. The throw statement is used for this purpose. The general forms of throwing an exception are as follows:

throw exception _obj;

For example, the following statement throws an argument exception explicitly. Throw new ArgumentException(“Exception”):

C#: Exception Handling:

using system;
class simple
{
public static void main()
{
try
{
throw new DivideByZeroException("Invalid Exception");
}
catch(DivideByZeroException e)
{
Console.writeLine("Exception");
}
Console.writeLine("Last Statment");
} // end of the main method
} // end of the main class

Exception of OverFlow

Exception for overflow and stack empty Exceptions in a class is created for stack Data Structure: Stack Over Flow Exception is thrown for execution stack overflow errors, typically in case of a very deep or unbounded recursion. Stack Overflow Exception uses the FOFO policy to handle upcoming data, it stands for First in First out.

C# provides a list of values for an instance of StackOverFlowException, set the StackOverFlowException.#ctor constructors.

Syntax:
[Serializable]
public sealed class StackOverFlowException: SystemException.

Example:

using system:
using system.io:
namespace StackOverflowSpace
{
// This class contain the entry point for every simple program
// that will illustrate the StackOverFlowException. the exception will be thrown inside the function call but will keep traversing up the stack until we catch it inside main.

class StackOverFlowExample
{
// entry point for the simple
public satic void main()
{
// attempt to call an infinitely recursive function
try
{
Recursive.infinitelyRecursive();
}
// this will fire when the recursion went to deep
catch(System.StackOverFlowException overflowexcept)
{
Console.writeLine("overFlowExcept.message");
Console.writeLine("Program will now end");
return;
}
Console.writeLine("This line will never executed");
} // end of main function
} // end of class stack overflow

class recursive
{
public static void main()
{
INfiniRecurse()
return;
}
} // end of the class recursive
} // end of the StackOverFlowSpace Namespace

Stack Empty Exception

Stack Empty Exception

Stack Empty Exception: Stack Empty Exception is the compile-time exception, it is not a runtime exception. This exception simply follows the FIFO policy(First in First out).

Example:

using system;
using system.Collections.Generic;
using system.Linq;
namespace sample
{
class program
{
public static void main(string[]args)
{
Stack<string> str=new Stck<string>(20);
string strdata=""
if(str.Any())
{
strdata=str.Pop();
}
strdata.Push("asdf")
if(str.Any())
{
strdata=str.Pop()
}
Console.writeLine(strdata);
} // end of the main function
} // end of the class program
} // end of the namespace

Conclusion

In this post, I have described the Exception (Run time and Compile time exception). An Exception is an unwanted error that occurs at the time of program execution. Exceptions do not occur at compile-time, they always occur at runtime and the user does not know in advance that what exception can be there in the program.

Moreover, I have described how Exceptions handle in the C#. Also, I  have explained about different exceptions that occur at the time of the program execution. Exceptions like Arithmetic Exception, stack empty exception, etc. We can catch multiple exceptions for the same try block. I have clearly shown how a programmer throws an exception and handle an exception.
I hope this blog is valuable and beneficial for the learner. Thank you!

Leave a Comment