Results 1 to 2 of 2

Thread: Exception handling????

  1. #1

    Thread Starter
    Evil Genius alex_read's Avatar
    Join Date
    May 2000
    Location
    Espoo, Finland
    Posts
    5,538

    Exception handling????

    Hi people! At the moment, I use this type of routine in VB:
    VB Code:
    1. Sub Test()
    2.     Dim obj as Object
    3.  
    4.     Try
    5.         ' obj.new
    6.         ' obj.property
    7.     Catch ex as Exception
    8.         ' handle obj exception
    9.     Finally
    10.         If not (obj is nothing) then
    11.             obj = nothing
    12.         End If
    13.     End Try
    14. End Sub
    From doing the same in this c# language, this:
    Code:
    void Test() {
        object obj
    
        try {
            // obj.new
            // obj.property
        }
        catch Exception ex {
            // handle obj exception
        }    
        finally {
            if (obj !=null) {
                obj = null
            }
        }
    }
    Generates a "Use of unassigned local variable" exception for the obj variable. It looks like my choices are:

    1) To declare and set with the New() keyword, any objects, right at the top of the method - which means a performance hit as I'm not just referencing them only when I need to, or...

    2) To put the calls to set the object to null within only the try block. Then if an exception's generated before this line, just leave it to the garbage collector only to clear the object from memory.

    Surely this can't be right can it? I though C# was at least the same, if not more efficient than VB?

    Please rate this post if it was useful for you!
    Please try to search before creating a new post,
    Please format code using [ code ][ /code ], and
    Post sample code, error details & problem details

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Exception handling????

    Simply assign "null" to your variable and you'll have no issues, i.e. object obj = null;

    Edit:
    Be aware, though, that setting your object reference to null in the Finally block is still leaving things to the garbage collector. You are not actually disposing your object but simply removing all references to it. This just tells the garbage collector that it can clean up your object whenever it is ready. Unless your object doesn't go out of scope for some time after this section of code setting your variable to null does not really achieve anything, although it may still be good practice. If you want to free the resources held by your object you need to explicitly dispose it before setting your reference to null.
    Last edited by jmcilhinney; Jun 6th, 2005 at 11:16 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width