Results 1 to 25 of 25

Thread: [RESOLVED] Constructors and exceptions

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2007
    Location
    cobwebbed to PC
    Posts
    311

    Resolved [RESOLVED] Constructors and exceptions

    Hi Folks

    I am struggling along with my first few classes and some custom exceptions. If I have the following:

    vb Code:
    1. Dim currentDuts As New Dictionary(Of Integer, DeviceUnderTest)
    2. Dim newDutKey As Integer = currentDuts.Count + 1
    3. Try
    4.     currentDuts.Add(newDutKey, New DeviceUnderTest(LocationBox.Text))
    5. Catch ex As Exception
    6. '...
    7. End Try

    A) What happens to the newly created DeviceUnderTest object if currentDuts.Add() fails, is it destroyed again, or is it floating somewhere in memory?

    B) For that matter what happens if New DeviceUnderTest() fails? Does .Add() also fail? I'm guessing yes, but in that case, if I want to filter the exceptions by type, which exception will 'ex' be, the one from New() or the one from .Add()?

    Also;

    C) Should the tests on a constructors arguments be before or after MyBase.New(), I assume if the tests are after, any exceptions they cause to be thrown would not have prevented the object from being created... Is that the case? (Or maybe it's totally irrelevant?)

    i.e.
    vb Code:
    1. Public Class DeviceUnderTest
    2.     Public Sub New(argument As String)
    3.         'Should MyBase.New() go here...
    4.         If argument = wrong Then
    5.             Throw New wrongArgumentException
    6.         Else
    7.             myPrivateVar = argument
    8.         End If
    9.         'Or should MyBase.New() go here?
    10.     End Sub
    11.     '...
    12. End Class

    Thanks
    Last edited by wolf99; Jul 23rd, 2013 at 03:12 PM.
    Thanks

  2. #2
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: Constructors and exceptions

    A & B: Add can only fail if the Device is Nothing which can only happen if the New failed. There's only one possible cause of the exception here!

    C: The New sub doesn't create the object, it merely initialises values and so on within it. If you think about it, the code can't run if the object doesn't 'exist'! So it's largely irrelevant where you put the MyBase part of it. It may even be possible to leave it out altogether. There's no guarantee that it does anything!
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  3. #3
    PowerPoster
    Join Date
    Mar 2002
    Location
    UK
    Posts
    4,780

    Re: Constructors and exceptions

    What about a duplicate item in the dictionary?

    MyBase.New should go first.

  4. #4
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: Constructors and exceptions

    What about a duplicate item in the dictionary?
    There can't be a duplicate item in the dictionary as every value is a New instance. If it's possible to get a duplicate key then that's a coding problem that should be sorted out long before you're thinking about what exceptions to catch!

    MyBase.New should go first.
    It can. You might prefer it. But there's no 'should' about it. The only circumstance that might require it to be would be if you were setting values that would be directly overwritten by MyBase.New but there's no indication that that's the case here. It might well be that MyBase.New is an empty sub in this case as I've suggested (it would be a trivial matter to find out).
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  5. #5

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2007
    Location
    cobwebbed to PC
    Posts
    311

    Re: Constructors and exceptions

    Hi dunfiddlin, Grimfort

    What about if the .Add exceeds the maximum number for the dictionary collection? (If the maximum number of items is a property of collections, which I thought it was but now cant find a reference for...)

    Either way, if the deviceUnderTest object is created wherever the constructor throws an exception, that means I need to dispose of it in the catch, and as you say the .add() should work regardless of constructor exception, that can be done with currentDuts.Remove() right? does that actually dispose of the object as well?

    Thanks
    Thanks

  6. #6
    PowerPoster
    Join Date
    Mar 2002
    Location
    UK
    Posts
    4,780

    Re: Constructors and exceptions

    http://msdn.microsoft.com/en-us/library/707s02fy.aspx forgive the bad formatting, on my tablet. There are times when it has to be the first line, which I suppose is why I went with should. I'm sure read about it somewhere in coding guidelines as well. Either way works.

  7. #7
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: Constructors and exceptions

    What about if the .Add exceeds the maximum number for the dictionary collection?
    How many were you thinking of having? The only limit that I'm aware of is memory and if you can bust that then you should be doing this on a Cray not a PC!

    currentDuts.Remove()
    Er ... you can't remove what was never added! I'll have a quick play about to make sure but I think garbage collection will take care of this.
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  8. #8
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: Constructors and exceptions

    Yup, there is no addition to the dictionary of either key or value and the failed object will simply waft away into non-existence.
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  9. #9

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2007
    Location
    cobwebbed to PC
    Posts
    311

    Re: Constructors and exceptions

    What I mean is, you say the object will still be created - if this is the case, even if the New() throws an exception, the object will still be added to the dictionary. Thus I should need to remove it again as it has been incorrectly initialized by the failed New().

    If it has been added, also without exception by .Add(), then .Remove() should do the trick.

    I dont think I'll have that many objects in the dictionary (else I'd be putting Websters out of business - ooh bad puns!) I just thought I remembered there being a maxCount or maxNumber property of collections that could be set by the programmer that I would have thought would subsequently need some kind of corresponding OverMaxCountException, but I must have mis-remembered, as I cannot find where I read it on MSDN now!

    Thanks
    Thanks

  10. #10
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Constructors and exceptions

    I think you misinterpreted what was said... if the constructor fails for what ever reason, the result is Nothing... technically, Nothing is a valid non-value and can be added to a dictionary... but no object ever existed, so there is nothing to return... additionally this is predicated on the fact that the constructor does NOT have any error handling and lets the calling code deal with the exception... However... it is possible that some object's constructor will handle any KNOWN exceptions quietly, allow the object to be created, but may set an internal state that may render it invalid. But generally when ever there is an error in the constructor the error bubbles out AND THE OBJECT IS NOT CREATED.

    Regarding the MyBase.New issue - it should go first, especially if it's an inherited object, and let it do what it needs to do, then you handle your initialization afterwards. Operative word is "should" ... it's the generally recommended practice, but... there are times when you may want to delay that initialization and/or bypass it all together. I think the generally accepted good practice is to do it first, let the base object initialize itself first.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  11. #11
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,109

    Re: Constructors and exceptions

    Putting the MyBase.New is a very good practice. Suppose the base class initializes some variable to some value which the derived class constructor then makes use of. Until MyBase.New has executed, the base class is not initialized, so the derived class dare not use any part of the base class. That's dangerous practice.

    By the way, when it comes to the first part, I think you should always have a test app for this kind of situation. All you would need to do is come up with some dummy class that has nothing in it but a constructor with a line that will certainly throw an exception. You can then create a dictionary keyed on whatever you want (probably an Integer), and try the code you have to see what is happening. That's probably what dunfiddlin did. You could step through the addition of the item to the dictionary and see what is in the dictionary before and after the attempted addition. I'd bet that most people on here have some form of test app to try out things they aren't quite sure about.

    Also, the maxsize sounds like something from List(of T), which either has, or had, some property like that. It wasn't a limit, though, it was a seldom used property that gave you some information about how the collection was managing things. I wouldn't have been surprised if Dictionary had the same thing, though perhaps the Dictionary manages memory differently than the List (of T) does.
    Last edited by Shaggy Hiker; Jul 23rd, 2013 at 09:47 PM.
    My usual boring signature: Nothing

  12. #12
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Constructors and exceptions

    I don't remember if it was List or ArrayList, but one of them (maybe both) has it, and it's not a hard limit... I want to say it's an initialization method... if I'm going to add 10 items to the list/arraylist, then I can predefine it so that it allocates enough space for those 10 objects.... but I can still add more than that. It's to save time when adding the object, as the space is already allocated.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  13. #13
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Constructors and exceptions

    As far as MyBase.New goes, you don't have a choice. It has to be the first statement of a constructor. Try putting it at the end. Go on, I'll wait.

    What's that? You got an error message "Constructor call is valid only as the first statement of an instance constructor."? The constructors in a base class/derived class pair are not analogous to an overridden method. The base class constructor runs first, then the derived class. Always. Yes, even if you don't specify MyBase.New in the derived class. Consider this program:
    vbnet Code:
    1. Module Module1
    2.  
    3.     Sub Main()
    4.         Dim derived As New DerivedClass
    5.  
    6.         Console.ReadLine()
    7.     End Sub
    8.  
    9. End Module
    10.  
    11. Public Class BaseClass
    12.     Sub New()
    13.         Console.WriteLine("BaseClass Constructor running")
    14.     End Sub
    15. End Class
    16.  
    17. Public Class DerivedClass
    18.     Inherits BaseClass
    19.  
    20.     Sub New()
    21.         Console.WriteLine("DerivedClass Constructor running")
    22.     End Sub
    23. End Class

    You'll find it outputs two lines to the console:
    Code:
    BaseClass Constructor running
    DerivedClass Constructor running
    So if the base class constructor is called without specifying MyBase.New in the derived constructor, what is the point of it? Well, consider this program:
    vbnet Code:
    1. Module Module1
    2.  
    3.     Sub Main()
    4.         Dim derived As New DerivedClass
    5.  
    6.         Console.ReadLine()
    7.     End Sub
    8.  
    9. End Module
    10.  
    11. Public Class BaseClass
    12.     Sub New(callerName As String)
    13.         Console.WriteLine("BaseClass Constructor running (called from {0})", callerName)
    14.     End Sub
    15. End Class
    16.  
    17. Public Class DerivedClass
    18.     Inherits BaseClass
    19.  
    20.     Sub New()
    21.         Console.WriteLine("DerivedClass Constructor running")
    22.     End Sub
    23. End Class

    This program has a compile time error:
    First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class 'DerivedConstructorTest.BaseClass' of 'DerivedConstructorTest.DerivedClass' does not have an accessible 'Sub New' that can be called with no arguments.
    You have to provide the arguments for the parameters of the constructor somehow, so in this instance you need a MyBase.New call in order to supply them:
    vbnet Code:
    1. Module Module1
    2.  
    3.     Sub Main()
    4.         Dim derived As New DerivedClass
    5.  
    6.         Console.ReadLine()
    7.     End Sub
    8.  
    9. End Module
    10.  
    11. Public Class BaseClass
    12.     Sub New(callerName As String)
    13.         Console.WriteLine("BaseClass Constructor running (called from {0})", callerName)
    14.     End Sub
    15. End Class
    16.  
    17. Public Class DerivedClass
    18.     Inherits BaseClass
    19.  
    20.     Sub New()
    21.         MyBase.New("DerivedClass")
    22.         Console.WriteLine("DerivedClass Constructor running")
    23.     End Sub
    24. End Class

  14. #14
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Constructors and exceptions

    There seems to be some confusion on this matter too:

    Quote Originally Posted by wolf99 View Post
    A) What happens to the newly created DeviceUnderTest object if currentDuts.Add() fails, is it destroyed again, or is it floating somewhere in memory?

    B) For that matter what happens if New DeviceUnderTest() fails? Does .Add() also fail? I'm guessing yes, but in that case, if I want to filter the exceptions by type, which exception will 'ex' be, the one from New() or the one from .Add()?
    Let's change the question slightly so that we're not going off on tangents as to whether .Add() can ever throw exceptions. Here's the code I'm going to think about:
    vbnet Code:
    1. Module Module1
    2.  
    3.     Sub Main()
    4.         Try
    5.             SomeMethod(New SomeObject)
    6.         Catch exception As Exception
    7.             ' Error handling
    8.         End Try
    9.     End Sub
    10.  
    11.     Sub SomeMethod(someOBject As SomeObject)
    12.         ' Do something
    13.     End Sub
    14.  
    15. End Module
    16.  
    17. Public Class SomeObject
    18.     Sub New()
    19.         ' Do something
    20.     End Sub
    21. End Class

    So, question A becomes what happens to the instance of SomeObject if SomeMethod throws an exception? I'm going to assume we're talking about an immediate exception whereby SomeMethod has done no work (such as adding the reference to a field/collection).

    In this instance, there are no references to the newly created object, and therefore it is eligible for Garbage Collection the next time it kicks in.
    In slightly different code, we might have the following in the Try block:
    vbnet Code:
    1. someObject = New SomeObject
    2. SomeMethod(someObject)

    Now what happens is dependent on the scope of the someObject variable and what mode the code has been compiled in. In Debug mode, the object is not eligible for Garbage Collection until the variable has another object assigned to it or the variable goes out of scope. In Release mode, the compiler will do more optimisations and the object would be eligible for Garbage Collection after the code could determine the variable was never used again.

    So, in summary, GC takes care of it for you, don't worry about leaking memory.

    For Question B, we want to know what happens if the constructor of SomeObject throws an exception. SomeMethod, in this case, is not called. Whether you consider that as "failing" is up to you, but the end result is that the side effects of SomeMethod (adding the reference to a collection for example) do not occur. If a constructor throws an exception, it does not return an object, the runtime will clean up (GC is still tracking any objects that may have been created in the constructor, and will clean them up as normal), and the exception will bubble up, execution will resume at the first relevant Catch handler.

    [Edit: Just wanted to add: I, personally, would think very hard before I coded a constructor that could throw an error. Generally my constructors simply set fields from constructor arguments, if there's heavy lifting to be done other than that, consider an additional method (like the Open() method on network connections - the constructor doesn't open the connection, it just initialises an object with the server address etc.)]
    Last edited by Evil_Giraffe; Jul 24th, 2013 at 06:16 AM.

  15. #15

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2007
    Location
    cobwebbed to PC
    Posts
    311

    Re: Constructors and exceptions

    Thanks All
    Thanks

  16. #16
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: [RESOLVED] Constructors and exceptions

    What's that? You got an error message "Constructor call is valid only as the first statement of an instance constructor."?
    You can go off people, you know! Apologies to all for my ignorance/stupidity/pig headedness etc. I'm blaming the weather (it's hot in July ... no blue-blooded Englishman should be expected to be able to cope with that kind of thing!)
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  17. #17
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: [RESOLVED] Constructors and exceptions

    Quote Originally Posted by dunfiddlin View Post
    (it's hot in July ... no blue-blooded Englishman should be expected to be able to cope with that kind of thing!)
    *cough*checkmylocation*cough*


  18. #18
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: [RESOLVED] Constructors and exceptions

    Pah. Suffolk's had it easy. Add at least 3 degrees to every Suffolk high of the past week and you'll get the lower end of what we've had to put up with!

    This is exactly why I swore I'd never move South again but did Fate listen? Did it heck as like! Have I mentioned how much I hate my life at all?
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  19. #19
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,109

    Re: [RESOLVED] Constructors and exceptions

    What's with that location? Did you want a change of hemisphere, or are you just chasing summers around the globe?
    My usual boring signature: Nothing

  20. #20
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: [RESOLVED] Constructors and exceptions

    Chasing summers and ending up in the UK? That's not so logical.

    Nah, I'm from the UK, but spent two years in Sydney as a work assignment.

  21. #21
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,109

    Re: [RESOLVED] Constructors and exceptions

    Don't be so down on your summers. We have fires burning all around. They rarely make more than the local news, because it happens EVERY year. By July, you go where it isn't burning if you want recreation. August is even worse.

    Some of our forests call their destructor before the constructor has finished operating. I sometimes expect to get stack overflow errors due to the perpetual loops.
    My usual boring signature: Nothing

  22. #22
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: [RESOLVED] Constructors and exceptions

    Quote Originally Posted by Shaggy Hiker View Post
    Some of our forests call their destructor before the constructor has finished operating.
    Err, you know that can happen in .NET as well, right?
    http://ericlippert.com/2013/06/10/co...n-destruction/

    [Edit: also, kudos to us, we appear to have re-railed the conversation on the original topic]

  23. #23
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: [RESOLVED] Constructors and exceptions

    Quote Originally Posted by Shaggy Hiker View Post
    Don't be so down on your summers. We have fires burning all around. They rarely make more than the local news, because it happens EVERY year. By July, you go where it isn't burning if you want recreation. August is even worse.

    Some of our forests call their destructor before the constructor has finished operating. I sometimes expect to get stack overflow errors due to the perpetual loops.
    My front yard has been experiencing a stack overflow as well. Apparently while handling the Rain event, an infinite loop got created. Fortunately the thread got suspended for a few day and I was able to call the drain method.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  24. #24
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,109

    Re: [RESOLVED] Constructors and exceptions

    I have always tried to avoid a constructor ever doing anything other than finishing properly. That might result in a member being set indicating that not everything got built, but my goal has always been that at the end of a call to New, a viable object exists. I didn't know that you could destruct from the constructor because I was always under the impression that doing anything of the sort would result in problematic code.
    My usual boring signature: Nothing

  25. #25
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: [RESOLVED] Constructors and exceptions

    Idealy, yes, a constructor will always result in a viable object... I'm trying to think of a case... ANY case... where an error threw out an object in a constructor such that it was unusable, and ... I can't think of one... usually when I do run into a problem on a call to a constructor, it's a problem with what I am passing to the constructor (like a null where a string is expected, or a nothing object, etc). Usually that's where the problem lies, something passed into it isn't in the correct state. Rarely is it due to a problem with the constructor itself.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

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