Exception handling code in case of return type of function

Topics: Exception Handling Application Block
May 26, 2009 at 10:10 AM
Edited May 26, 2009 at 10:12 AM

Normally in ent lib HOL as well as documentation I found the code to handle exception in catch block  is

bool rethrow = ExceptionPolicy.HandleException(ex, "Logging Policy");

if (rethrow)

throw;

But if the method has a return type then this code in catch block gives an error :

Not all code paths return a value

Similarly, in global.asax it gives an error: 

A throw statement with no arguments is not allowed outside of a catch clause.

Please suggest the right approach in such cases.

Thanks

ArnabC

May 26, 2009 at 10:13 AM
Edited May 26, 2009 at 10:18 AM

Sorry for the previous post, I answered too early.  This code should be placed inside a try catch block, or better yet, inside the catch block.  And if your method has a return type, make sure you're still returning something even after an exception has been thrown.

Sarah Urmeneta
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com

May 26, 2009 at 10:29 AM

Thanks Sarah for the reply.

I'm adding the code in catch block as shown below.

public string MyFunctionName()
    {
        try
        {
            //Some Business Functions
            return "message";
        }
        catch (Exception ex)
        {
            bool rethrow = ExceptionPolicy.HandleException(ex, "Logging Policy");
            if (rethrow)
                throw;

        }

    }

As you said I can return empty string if the return type is string, but what happens if my return type is a complex object. What do I do in such cases?

Also in case of global.asax?

Thanks

ArnabC

May 26, 2009 at 10:52 AM

You can return null for complex objects.  In the case of the one in the global.asax, you could do something like this: 

 

 

 

 

Exception ex = Server.GetLastError();<font size="2">

 

</font>

if (ex != null)

{

<font size="2">

 

</font>

ExceptionPolicy.HandleException(ex, "Exception Policy");<font size="2">

Response.Redirect(

</font>

"~/Error.aspx");

}

This of course prevents you from throwing the exception if the posthandling action is set to any other than None.  But this is I think is a better way of handling exception in web apps if you don't want to show the user what is the exact exception that occured.

 

Sarah Urmeneta
Global Technology and Solutions
Avanade, Inc.

entlib.support@avanade.com

May 26, 2009 at 1:20 PM

Thnx

Arnab C