Exception handling interview questions and answers

Can we use multiple finally blocks inside the method?

Yes, you can write the multiple finally block inside the method. For every try block, you can have finally.

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 the try block?

Yes, It is possible to keep finally inside the try block. Shown in above example.

Is it possible to keep multiple catch block for the try block?

Yes, Is is possible. You can have multiple catch blocks associated with a try block, but only a single catch block can ever handle your exception.

 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 an try block without catch/finally block. you have to write one of the blocks either catch or finally.

try
{

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

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

 

Can we write try block only with finally block?

Yes, You can write the try only with finally block.

Close

About The Author

Deependra Kushwah
Deependra kushwah is a member of the fastest growing bloggers community "betechnical", Author, Youtuber, and hardcore Coder. I love writing code in different languages, I also write blogs on tech tutorials, gadgets review and also post some technical videos on youtube on many topics.

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