You will learn followings
- Nesting of try-catch block in C#
- Multiple Catch Blocks in C#
- Finally Block in C#
Nesting of try-catch block in C#
In this article we’ll discuss how to work with Nesting of try-catch block in C# program with the help of example. In C#, you can nest the try-catch block and also can use multiple catch blocks in C# to handle different types of exceptions.
What you'll learn below:
Can try block be nested in C#?
Yes, nesting of the try-catch block is allowed in C#. The nesting of try-block means one try block can be nested into another try block. The various programmer uses the outer try block to handling major exceptions, whereas the inner try block for handling normal or minor exceptions. My personal opinion is that nesting of try-catch reduces the readability of the program so we should use is where it is highly required.
Important points about try-catch block in C#
- It is necessary condition that a try block must be followed by a catch or finally blocks because if you use a finally block without a catch and if error occurred then it will be bubbled up to parent method catch block.
- If any error occurred in inner, try block then immediately after the exception control is transferred to inner catch and all next code (in inner try block) is skipped from execution.
- If an exception raises in the inner try block that is not caught by the inner catch block, then that exception is promoted to the outer/parent try block. In this whole process nature/type of exception is changed.
Syntax:
Scenario: Let’s create 2 methods, parent and child method. Child is getting called by parent and both have try-catch block in them. If some error occurred in child method, then how it changes in parent method, let’s see below
If inner, try-catch in child method is creating some collection object and on error (may be network connection error) it will return null in collection object to its parent method and parent method try block will try to extract some data form it then object reference error may occur in outer block i.e., in parent function whereas in inner catch block error nature/ type was different
Nesting of try-catch block in C# in same method:
// START of outer try block
SqlConnection connection = new SqlConnection();
try
{
//START of inner try-catch block
try
{
connection.Open();
}
catch(IndexOutOfRangeException ex)
{
// code...
}
//END of inner try-catch block
}
catch(Exception ex)
{
// code...
}
// END of outer catch block
In above example I did not add IF check while opening SQL connection. In case Connection already opened then it will give error. Inner catch block will not handle it because it is designed to handle different type (IndexOutOfRangeException) of exception and error will go to its parent catch block. This is the way how nested try-catch works.
Can we use try without catch C#?
Yes, but we need to use it with finally, like try-finally but if any error occurred in Try that will not get handled and will be moved to outer block catch or to parent method.
Do try-catch blocks or its nesting hurt performance?
Yes, try-catch will "hurt" performance. Although it is good practice to have try-catch in your code to prevent unhandled exception but massive use of this can defiantly slow down the program because compiler also need time to compile/ execute this extra line of codes.
In this article, we’ve learned how to do nesting of try-catch blocks in C#. You can also check our related article multiple catch blocks in C#. I believe after reading this article you’ll be able to use this in your daily development practices. You can also check more on Microsoft Learn.
Are you willing to check more on C# then please visit HERE
Multiple Catch Blocks in C#
In this article we’ll discuss how to use multiple catch Blocks in C# program with the help of some examples. In C#, you can use more than one catch block with the try block. Generally, multiple catch block is used to handle different types of exceptions means each catch block is used to handle different type of exception.
What you'll learn below:
C# does not allow you to use multiple catch block for the same type of Exception
If you use multiple catch blocks in C# for the same type of exception, then it will give you a compile-time error and a catch block is always preceded by the try block i.e., catch block can never be used standalone without try.
In general, the catch block is executed within the order in which they are written in the program. If the given type of exception is matched with the first catch block, then first catch block executes and the remaining of the catch blocks are ignored. And if the starting catch block is not suitable for the exception type, then compiler search for the next catch block until it gets desired CATCH block.
Try with multiple catch blocks in C#: Syntax
What must take care while using multiple catch blocks in C#?
We know that Exception class is main abstract class, all other exception classes can be inherited from it. So, the point which need to take care is Exception class must be in last catch block not in other catch blocks, else it will catch all the errors in its block and rest of remaining CATCH blocks will never be executed.
Code sample:
class ExceptionTest
{
static void Main(string[] args)
{
int num1=1;
int num2=0;
int num3=0;
try
{
// we’ll try to divide 1 by Zero to get error.
num3 = num1 / num2;
}
catch (DivideByZeroException exp)
{
Console.WriteLine(exp.Message);
}
catch (FormatException fe)
{
Console.WriteLine("Exception: Invalid format");
}
catch (Exception ex)
{
Console.WriteLine("exception generated="+ ex.Message);
}
}
}
An above example we see how to work with multiple Catch blocks now in below example we’ll how to add switch case pattern under one CATCH.
Single Catch Blocks with Switch Pattern
To separately manage all exceptions in one catch block, we can utilize the switch pattern syntax too. Let’s create a sample as below:
try
{
Int testValue = 1/0;
}
catch (Exception ex)
{
switch (ex)
{
case FormatException:
Console.WriteLine("Format Exception!");
break;
case DivideByZeroException:
Console.WriteLine("Divide By Zero Exception!");
break;
case OverflowException:
Console.WriteLine("Overflow Exception!");
break;
}
}We catch all the exceptions in a single CATCH block and separate them using a switch-case pattern. Above mentioned, switch (ex) can recognize the type of the “ex” variable and compare it with each case. On the other hand, we can also use the if-else pattern instead of a switch-case model but considering performance switch must be used for better performance.
Single Catch Blocks with or operator
We can use one CATCH block and instead of switch case we can put II i.e. OR operator in between different type of exceptions and specified type of errors will log under that block. For more detail, please check below code sample:
Multiple Catch Blocks vs Single Catch Block
Once the application throws the exception the question is, do multiple catch blocks have better performance or a single catch block? So, after throwing an exception, the try-catch should have a switching pattern for delivering the exception to the first best case or we can also use main abstract exception class which is Exception class
On the other hand, when we use multiple catch blocks, the compiler defines the switching model automatically. But if we write a single catch block, we should specify that switching pattern and while implementing it manually developer must use Switch case rather than if- else for the better performance.
In this article, we’ve learned how to catch multiple exceptions using different approaches. First is using multiple catch blocks and second is using switch case in single catch block. I believe after reading this article you’ll be able to use this in your daily development practices. You can check more on Microsoft Learn.
Are you willing to check more on C# then please visit HERE
Finally Block in C#
In this article we’ll talk about Finally Block in C#. What and where we can use this and about its PROS and CONS too. If you haven’t checked my previous article on “Multiple Catch blocks in C#” then please check that first for better understanding.
What we’ll cover in this article:
Important points of Finally Block in C#
- Finally block always execute regardless of any exception.
- Multiple finally blocks in the same try block are not allowed.
- Finally block is always executed after the try and catch blocks, but before control transfers back to its origin calling method.
- It does not support return, continue, break statements because it does not allow controls to leave the finally block until it executes completely.
- You can also use finally block only with a try block means without a catch block but in this situation, no exceptions are handled.
What is finally block in C#?
'Finally' is a reserved keyword in C#. It is a block of statements that are always executed, regardless of any exceptions that occur in an application. It is used optionally with the "try/catch/finally" or "try/finally" block and guarantees the execution of any code that must be executed before exiting the "try" block, regardless of the success or failure of the application's execution.
As you can see below, in two ways we can write the finally block in C#. They are as follows:
- Try, Catch, and Finally: In this case, the exception will be handled by the CATCH block, no abnormal termination occurs in this case and “finally” block code gets executed at any cost.
- Try and Finally: In this case, abnormal termination will occur because of missing CATCH block but even after that finally blocks will get executed.
var connection = new SqlConnection();
connection.Open()
try
{
// execute a code
}
catch(Exception ex)
{
// handle an exception
}
finally
{
// do all required cleanup
// if the code executes with or without an exception, we'll close connection here
connection.Close();
}
What, if finally re- throw error, let’s check below?
Whenever an exception occurs in the try block, control passes from the line that caused the exception to the relevant catch block (Check multiple CATCH block exception handler) and then to the finally block. Also, when an exception is re-thrown in a catch block, control transfers to the finally block. Next if exceptions again occur in finally then it will be bubbled up to its parent method Catch block. Thus, next code after the line (with in try) where the exception occurred will be skipped.
If your program contains “break", "goto", "continue" or "return" statement in Try block or due to any exception when control exits from try block, every time finally block is executed.
Additionally, exceptions should not be thrown explicitly in a finally block. If an exception occurs during the execution of a finally block, any code after the point where the exception is thrown will not execute, and current exception will propagate to the outer try block or to parent method try block.
Care should be taken not to explicitly transfer execution into or out of a finally block as this is not a valid transfer.
How to use finally in our C# program?
The execution of Finally block is to release resources, such as database connections, IO operations which are usually available in limited quantities. Using this disposal of resources occurs earlier than the garbage collector's finalization operation, thereby it is optimizing memory usages.
Conclusion: We should use “Finally” block when we work with IO operation or network connections etc. so that memory can be released.
Is this really required to use finally in C#?
Yes, one should use it to optimize the memory before Garbage Collector (GC) take care of it. Especially in case of IO streams and network connections.
What are Pros & Cons?
PROS: Considering the memory optimization one must use this in his/her daily development practices.
CONS: We know that finally block will execute once in the lifetime of that program, so developer should write code for object dispose or for memory optimization only. Any extra code can cause performance issues.
Can we skip finally block in C#?
Finally block of code always executes, irrespective of any Exception in program. You can never skip the execution of the final block.
In this article we tried to explain Finally Block in C# with Examples. I hope you enjoyed reading this article. For more information you can check out Microsoft learn.
For more information you can visit our C# Section for more such articles.




No comments:
Post a Comment