Solved

VB.net - unhandled exception in child component

Posted on 2002-07-05
12
876 Views
Last Modified: 2008-02-26
Hi

When trying to connect to a host using the wrong username/password in management.managementscope it reports an unhandled exception in mscorlib.dll even though I've put the code inside a try/catch block.

This is inside a method of my class:


  Dim Options as new Management.ConnectionOptions()
  Options.Username = "WrongUser"
  Options.Password = "WrongPassword"
  Dim Scope = new Management.ManagementScope("\\server\\root\cimv2", options)

Try
  Scope.Connect()
Catch e as Exception
  'handle error: this code will never run
End Try

Is there any way to handle unhandled exceptions in child objects ?
0
Comment
Question by:ToHo
  • 5
  • 4
  • 2
  • +1
12 Comments
 
LVL 4

Expert Comment

by:kpkp
ID: 7131696
try


 Dim Options as new Management.ConnectionOptions()
 Options.Username = "WrongUser"
 Options.Password = "WrongPassword"
 Dim Scope as Management.ManagementScope

Try
 Scope = new Management.ManagementScope("\\server\\root\cimv2", options)
 Scope.Connect()
Catch e as Exception
 'handle error: this code will never run
End Try
0
 
LVL 2

Author Comment

by:ToHo
ID: 7131700
kpkp: Tried to create the scope inside try statement, but with the same result.
0
 
LVL 4

Expert Comment

by:kpkp
ID: 7131708
are you sure the exception is being thrown from this bit of code?  Can you post the exception message and maybe a stack trace too?
0
 
LVL 2

Author Comment

by:ToHo
ID: 7131718
Message from MDE (inside the brackets):

"An unhandled exception of type 'System.UnauthorizedAccessException' occured in mscorlib.dll

Additional information: Access is denied."

Call Stack:

>     mscorlib.dll!System.Runtime.InteropServices.Marshal::ThrowExceptionForHR(__int32 errorCode = -2147024891) + 0x1c bytes    
      system.management.dll!System.Management.ManagementScope::InitializeGuts() + 0x24b bytes    
0
 
LVL 26

Expert Comment

by:EDDYKT
ID: 7131738
Have you try to use on error resume next
0
 
LVL 2

Author Comment

by:ToHo
ID: 7131744
EDDYKT: Yes, I've also tried using On Error Resume Next, but the messagebox displaying the exception still occurs.
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 4

Accepted Solution

by:
kpkp earned 200 total points
ID: 7131910
I think you're just getting a visual studio debugger message.  Try moving this line inside the try/catch...

Scope = new Management.ManagementScope("\\server\\root\cimv2", options)

...then using the project properties - set the configuration to release.  Try running the app using the 'debug/start without debugging' (CTRL+F5) menu.  The exception should then be caught and the code between the Catch and EndTry should run (although you don't have any code here).


0
 
LVL 2

Author Comment

by:ToHo
ID: 7131972
kpkp: Running the app without debugging makes the popup disappear. Is there no way to also remove this message in debug mode ?
0
 
LVL 4

Expert Comment

by:kpkp
ID: 7131993
Not that I know of.  I think maybe you have found a bug in studio!  Seems like the exception is being thrown on behalf of some win32 api function - maybe studio gets confused because it doesn't have the source for the api call, or the ThrowExceptionForHR method.  
0
 
LVL 2

Author Comment

by:ToHo
ID: 7131996
Ok. Thanks for your help.
0
 
LVL 28

Expert Comment

by:AzraSound
ID: 7132051
I had a sample project entitled "Global Exception Handling in VB.NET" that I posted at FreeVBCode.com, but it seems to have been removed sometime in the recent past:
http://www.freevbcode.com/ShowCode.Asp?ID=2545

It was written back during Beta 1, so perhaps they removed it because it was found to become a bit incompatible with the release version.  I will have to check on my home computer to see if I still have the source, but it may be worth a shot to see if it catches this exception not geing caught from within your Try...Catch block.
0
 
LVL 28

Expert Comment

by:AzraSound
ID: 7133966
I dont recall much about this sample, I wrote it about a year ago, and I dont have the release of .NET at home, but feel free to try it out and let me know if it even comes close to working (it works in Beta 1)


'GlobalExceptionHandler.vb
Imports System.Threading
Imports System.Drawing
Imports System.ComponentModel
Imports System.WinForms



'***************************************************************************
'
' Module Name: GlobalExceptionHandler
' Purpose: Handle all unhandled exceptions that occur during run-time
'                  execution of your program
'
'***************************************************************************

Public Module GlobalExceptionHandler
      Public Const vbCrLf As String = CChar(13) & CChar(10)
      
      
      'startup sub for program
      Sub Main()
            Dim cGEH As GlobalErrorHandler = New GlobalErrorHandler()
            
            
            'create delegate to handle ThreadException event of Application object            
            AddHandler Application.ThreadException, (AddressOf cGEH.OnThreadException)
            
            'run test form            
            Application.Run(New frmTest())
      End Sub
      
      
      
      
      'the class that does our exception handling      
      Private Class GlobalErrorHandler
            
            'application throws an exception handled here if not handled
            'locally within the procedure in which the exception occurred      
            Public Sub OnThreadException(ByVal sender As Object, ByVal e As ThreadExceptionEventArgs)
                  ShowErrorInfo(e.Exception)
            End Sub
            
            Private Sub ShowErrorInfo(ByVal e As Exception)
                  Dim frm As frmErrReport = New frmErrReport()
                  
                  'fill in error information on form
                  With frm
                        .txtStackInfo.Text = e.StackTrace
                        .txtSource.Text = IIf(e.Source = "", Application.ActiveForm.ToString, e.Source).ToString
                        .txtErrMsg.Text = e.Message
                        .txtErrInfo.Text = e.TargetSite.Name & GetParamInfo(e.TargetSite)
                  End With
                  
                  frm.ShowDialog()
            End Sub
            
            
            
            'get parameter information about the method that raised the exception
            Public Function GetParamInfo(ByVal ts As System.Reflection.MethodBase) As String
                  Dim strMsg As System.Text.StringBuilder = New System.Text.StringBuilder()
                  Dim pi As System.Reflection.ParameterInfo
                  Dim piArray() As System.Reflection.ParameterInfo
                  
                  
                  'get parameter information for the method                  
                  Try
                        piArray = ts.GetParameters
                  Catch
                        Return "()"                         'on error return no parameters
                  End Try
                  
                  Try
                        With strMsg
                              .Append("(" & vbCrLf)
                              
                              'loop through parameters
                              For Each pi In piArray
                                    .Append(IIf(pi.IsIn And pi.IsOut, "{in, out}", "").ToString)
                                    .Append(IIf(pi.IsIn And Not pi.IsOut, "{in}", "").ToString)
                                    .Append(IIf(Not pi.IsIn And pi.IsOut, "{out}", "").ToString)
                                    .Append(" " & IIf(pi.IsOptional, "[" & pi.Name & "]", pi.Name).ToString)
                                    .Append(" As " & pi.ParameterType.FullName & vbCrLf)
                              Next
                              
                              .Append(")")
                        End With
                        
                        Return strMsg.ToString
                        
                  Catch
                        Return ("Unable to process parameter information")
                  End Try
                  
            End Function
      End Class
      
      
      
      'form to display error information      
      Public Class frmErrReport
            Inherits System.WinForms.Form
            
            Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Integer, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Integer) As Integer
            Private Declare Function GetDesktopWindow Lib "user32" Alias "GetDesktopWindow" () As Integer
            
            'Private Function <System.Runtime.InteropServices.DllImport("shell32.dll")> ShellExecuteA(ByVal hwnd As Integer, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Integer) As Integer
            'End Function
            'Private Function <System.Runtime.InteropServices.DllImport("user32.dll")> GetDesktopWindow() As Integer
            'End Function
            
            
            
            Public Sub New()
                  MyBase.New()
                  
                  frmErrReport = Me
                  
                  'This call is required by the Win Form Designer.
                  InitializeComponent()
                  
                  'TODO: Add any initialization after the InitializeComponent() call
            End Sub
            
            'Form overrides dispose to clean up the component list.
            Public Overrides Sub Dispose()
                  MyBase.Dispose()
                  components.Dispose()
            End Sub
            
#Region " Windows Form Designer generated code "
            
            'Required by the Windows Form Designer
            Private components As System.ComponentModel.Container
            Public WithEvents txtErrInfo As System.WinForms.TextBox
            Public WithEvents txtErrMsg As System.WinForms.TextBox
            Public WithEvents txtSource As System.WinForms.TextBox
            Private WithEvents GroupBox3 As System.WinForms.GroupBox
            Private WithEvents GroupBox2 As System.WinForms.GroupBox
            Private WithEvents GroupBox1 As System.WinForms.GroupBox
            
            
            
            Private WithEvents btnReport As System.WinForms.Button
            Public WithEvents txtStackInfo As System.WinForms.TextBox
            Private WithEvents TabPage2 As System.WinForms.TabPage
            Private WithEvents TabPage1 As System.WinForms.TabPage
            Private WithEvents TabControl1 As System.WinForms.TabControl
            
            Dim WithEvents frmErrReport As System.WinForms.Form
            
            'NOTE: The following procedure is required by the Windows Form Designer
            'It can be modified using the Windows Form Designer.  
            'Do not modify it using the code editor.
            Private Sub InitializeComponent()
                  Me.components = New System.ComponentModel.Container()
                  Me.TabPage1 = New System.WinForms.TabPage()
                  Me.GroupBox1 = New System.WinForms.GroupBox()
                  Me.TabPage2 = New System.WinForms.TabPage()
                  Me.btnReport = New System.WinForms.Button()
                  Me.txtSource = New System.WinForms.TextBox()
                  Me.GroupBox3 = New System.WinForms.GroupBox()
                  Me.TabControl1 = New System.WinForms.TabControl()
                  Me.txtErrMsg = New System.WinForms.TextBox()
                  Me.txtStackInfo = New System.WinForms.TextBox()
                  Me.GroupBox2 = New System.WinForms.GroupBox()
                  Me.txtErrInfo = New System.WinForms.TextBox()
                  
                  '@design Me.TrayHeight = 0
                  '@design Me.TrayLargeIcon = False
                  '@design Me.TrayAutoArrange = True
                  TabPage1.Text = "Stack Info"
                  TabPage1.Size = New System.Drawing.Size(398, 270)
                  TabPage1.TabIndex = 0
                  
                  GroupBox1.Location = New System.Drawing.Point(10, 10)
                  GroupBox1.TabIndex = 0
                  GroupBox1.TabStop = False
                  GroupBox1.Font = New System.Drawing.Font("Arial", 8!, System.Drawing.FontStyle.Bold)
                  GroupBox1.Text = "Source  of  Error"
                  GroupBox1.Size = New System.Drawing.Size(378, 60)
                  
                  TabPage2.Text = "General Info"
                  TabPage2.Size = New System.Drawing.Size(398, 270)
                  TabPage2.TabIndex = 1
                  
                  btnReport.Location = New System.Drawing.Point(313, 312)
                  btnReport.Size = New System.Drawing.Size(96, 23)
                  btnReport.TabIndex = 1
                  btnReport.Text = "Report Error"
                  
                  '@design txtSource.Locked = True
                  txtSource.Location = New System.Drawing.Point(9, 18)
                  txtSource.Multiline = True
                  txtSource.ReadOnly = True
                  txtSource.BorderStyle = System.WinForms.BorderStyle.FixedSingle
                  txtSource.ScrollBars = System.WinForms.ScrollBars.Vertical
                  txtSource.Font = New System.Drawing.Font("Courier New", 8!)
                  txtSource.TabIndex = 0
                  txtSource.Size = New System.Drawing.Size(360, 34)
                  
                  GroupBox3.Location = New System.Drawing.Point(10, 172)
                  GroupBox3.TabIndex = 2
                  GroupBox3.TabStop = False
                  GroupBox3.Font = New System.Drawing.Font("Arial", 8!, System.Drawing.FontStyle.Bold)
                  GroupBox3.Text = "Method  Throwing  The  Exception"
                  GroupBox3.Size = New System.Drawing.Size(378, 87)
                  
                  TabControl1.Location = New System.Drawing.Point(6, 9)
                  TabControl1.Size = New System.Drawing.Size(406, 296)
                  TabControl1.SelectedIndex = 0
                  TabControl1.TabIndex = 0
                  
                  '@design txtErrMsg.Locked = True
                  txtErrMsg.Location = New System.Drawing.Point(9, 18)
                  txtErrMsg.Multiline = True
                  txtErrMsg.ReadOnly = True
                  txtErrMsg.BorderStyle = System.WinForms.BorderStyle.FixedSingle
                  txtErrMsg.ScrollBars = System.WinForms.ScrollBars.Vertical
                  txtErrMsg.Font = New System.Drawing.Font("Courier New", 8!)
                  txtErrMsg.TabIndex = 0
                  txtErrMsg.Size = New System.Drawing.Size(360, 51)
                  
                  '@design txtStackInfo.Locked = True
                  txtStackInfo.Location = New System.Drawing.Point(3, 2)
                  txtStackInfo.Multiline = True
                  txtStackInfo.ReadOnly = True
                  txtStackInfo.BackColor = Color.White
                  txtStackInfo.ScrollBars = System.WinForms.ScrollBars.Vertical
                  txtStackInfo.TabIndex = 0
                  txtStackInfo.Size = New System.Drawing.Size(393, 265)
                  
                  GroupBox2.Location = New System.Drawing.Point(10, 82)
                  GroupBox2.TabIndex = 1
                  GroupBox2.TabStop = False
                  GroupBox2.Font = New System.Drawing.Font("Arial", 8!, System.Drawing.FontStyle.Bold)
                  GroupBox2.Text = "Error  Message"
                  GroupBox2.Size = New System.Drawing.Size(378, 77)
                  
                  '@design txtErrInfo.Locked = True
                  txtErrInfo.Location = New System.Drawing.Point(9, 18)
                  txtErrInfo.ReadOnly = True
                  txtErrInfo.Multiline = True
                  txtErrInfo.BorderStyle = System.WinForms.BorderStyle.FixedSingle
                  txtErrInfo.ScrollBars = System.WinForms.ScrollBars.Vertical
                  txtErrInfo.Font = New System.Drawing.Font("Courier New", 8!)
                  txtErrInfo.TabIndex = 0
                  txtErrInfo.Size = New System.Drawing.Size(360, 61)
                  Me.Text = "Error Report Form"
                  Me.MaximizeBox = False
                  Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
                  Me.BorderStyle = System.WinForms.FormBorderStyle.FixedSingle
                  Me.ClientSize = New System.Drawing.Size(416, 339)
                  
                  TabControl1.Controls.Add(TabPage1)
                  TabControl1.Controls.Add(TabPage2)
                  Me.Controls.Add(btnReport)
                  Me.Controls.Add(TabControl1)
                  GroupBox2.Controls.Add(txtErrMsg)
                  TabPage2.Controls.Add(GroupBox3)
                  TabPage2.Controls.Add(GroupBox2)
                  TabPage2.Controls.Add(GroupBox1)
                  GroupBox1.Controls.Add(txtSource)
                  TabPage1.Controls.Add(txtStackInfo)
                  GroupBox3.Controls.Add(txtErrInfo)
            End Sub
            
#End Region
            
            
            Public Sub btnReport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReport.Click
                  Dim strMSg As System.Text.StringBuilder = New System.Text.StringBuilder()
                  
                  
                  'construct an email message to send exception info to techs
                  With strMsg
                        .Append("mailto:techs@urcompany.com")
                        .Append("?subject=Run-time Exception Occurred In " & txtSource.Text)
                        .Append("&body=Error Message: " & txtErrMsg.Text & vbCrLf & vbCrLf)
                        .Append("Error Info: " & txtErrInfo.Text)
                  End With
                  
                  'launch default internet email client
                  ShellExecute(GetDesktopWindow(), "Open", strMsg.ToString, "", "", 1)
                  
            End Sub
            
            
      End Class
      
      
      
End Module





If you include that code (and just move the Sub Main stuff if you already have one) you should be able to see if it catches any exceptions in your application.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

The object model of .Net can be overwhelming at times – so overwhelming that quite trivial tasks often take hours of research. In this case, the task at hand was to populate the datagrid from SQL Server database in Visual Studio 2008 Windows applica…
Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now