Ace Your Interview with these Exception Handling C# Questions

Share on facebook
Share on twitter
Share on linkedin
Share on pinterest

Can we use multiple finally blocks inside exception handling c# method?

Yes, we can write the multiple finally blocks in exception handling c#. For every try block, there needs to be either a catch block or finally block.

try
    {
        try
        {
        }
        finally
        {
            try
            {
                throw new ApplicationException();
            }
            finally
            {
                Console.WriteLine("cleanup code for third try block");
            }

            Console.WriteLine("cleanup code for second try block");
        }
    }
    finally
    {
        Console.WriteLine("cleanup code for first try block");
    }

Is it possible to keep finally inside a try block?

Yes, it is possible to keep finally inside a try block. An example for the same is shown above.

Is it possible to keep multiple catch blocks for a try block?

Yes, it is possible to have multiple catch blocks associated with a try block. However, only one catch block can ever handle an exception at a time.

 try
        {
           //Perform file related operation
          // Perform arithmatic operations 
        }
        catch (IOException ex)
        {
        
Console.Writeline("Called when file related exception occoured");

        }
        catch (ArithmeticException ex)
        {
Console.Writeline("Called when arithmatic operation 
                                related exception occoured");
        }
        catch (Exception ex)
        {
Console.Writeline("Unknown error occoured");
        }

 

Can we write try block without catch block?

No, It’s not allowed to write a try block without a catch/finally block. You have to write one of either catch or finally with each try block.

try
{

}
catch(Exception e){
}
------------------------------
try
{

}
finally{
}
-------------------------------
try{
//Not allowed
}

Can we write try block only with finally block in exception handling c#?

Yes, you can write a try block only with finally block.

Do you think this was a useful article for you? Feel free to provide your comments and concerns in the below comment section.
[yikes-mailchimp form=”1″]

Share on facebook
Share on twitter
Share on linkedin
Share on pinterest
Share on whatsapp
Share on email

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recommended for you
Connect With Us
Stay Connected
Subscribe to our newsletter today to receive updates on latest tech news, tutorials SEO tips many more.
Latest Articles