-5

How can I fix the below code so that finally part is not overwriten and I can see "This is a regular text" in lbl.Process's Text?

try
{
    grd_Order.SaveClicked(sender, e);
   //This is a button's Clicked event, which redirects to the same page after saving. 
}
catch
{
}
finally
{
   lbl_Process.Text = "This is a regular text"
   //Some more process
}

Edit: Whenever I simplify my code to make my question more understandable, I face the same thing. Many many misunderstandings.

HOY
  • 1,067
  • 10
  • 42
  • 85

6 Answers6

3

The finally block is working, the problem is that since you are redirecting to the same page, your lbl_Error is loosing its Text on postback.

Habib
  • 219,104
  • 29
  • 407
  • 436
2

If you put a breakpoint in your finally block you will notice that it always executes.

Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
1

There's no purpose for a finally block in the code you posted. Finally is used for cleanup. Move your code to the catch block if its for an error.

Do this:

try
{
    grd_Order.SaveClicked(sender, e);
   //This is a button's Clicked event, which redirects to the same page after saving. 
}
catch (Exception ex)
{
    lbl_Error.Text = "Error Occured " + ex.Message;
}

If the page redirects, that means an error didn't occur.

Lawrence Johnson
  • 3,924
  • 2
  • 17
  • 30
0

FYI:

Try block will execute the code it contains. If any exception is fired runtime, it will be caught by Catch.

And the Finally block will execute anyway.

jparthj
  • 1,606
  • 3
  • 20
  • 44
0

Finally always gets executed no matter your application throws exception or not.so you would expect the text to be overwritten

Prabhu Murthy
  • 9,031
  • 5
  • 29
  • 36
  • I am not actually tring to catch an exception, I have edited lbl_Error as lbl_Process to prevent missunderstandings. – HOY Oct 05 '12 at 07:02
0

I think your finally code block is working fine. Maybe your lbl text is lost because view state isn't enabled.

I advise you shouldn't write error messages in finally block. Finally block is used for code cleanup etc.

Here you need to put your error message in catch block.

A few more things about try catch finally

Try Block: wrap the code with try block where you are doing stuff (DB retrieval, connections, calling functions etc)

Catch block: The code wrapped in these blocks will be executed when there is an exception in try block, If you want you can have multiple catch blocks each for a specific exception.

Finally: Well finally block always runs regardless of exception or successful execution of try block and this block is used for code cleanup. consider this example - you created a db connection and then try to retrieve some data, you connection is successful but there is an error in your query then there will be an exception and it will come to catch block. what you need to do is to close the connection in finally that way you will not have any open connection.

I hope it will help.

Apocalyp5e
  • 181
  • 8