Tuesday 17 January 2012

Can we have try block without catch

Can we have try block without catch?

Yes.

We can write Try { } Finally { } block. In this case exception will be thrown in try block if it is but code inside finally block will execute.

Here any exception in CallFirstMethod() or CallSecondMethod() will be handled by MainMethod() and finally block will execute always to perform any cleanups for respective methods.

public void MainMethod()

{

try

{

CallFirstMethod();

CallSecondMethod();

}

Catch(Exception ex)

{

//handle exception

}

}

publiv void CallFirstMethod()

 {

try

{

//code

}

finally

{

//cleanups

}

}

publiv void CallSecondMethod()

{

try

{

//code

}

finally

{

//cleanups

}

}

No comments:

Post a Comment