Skip to content
Advertisements

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.

Advertisements

Deependra Kushwah View All

Deependra is a Senior Developer with Microsoft technologies, currently working with Opteamix India business private solution. In My Free time, I write blogs and make technical youtube videos. Having the good understanding of Service-oriented architect, Designing microservices using domain driven design.

What you think

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: