Resolved try catch doesn't catch

realolman

Member
Joined
Jan 2, 2017
Messages
15
Programming Experience
10+
I have a form that connects with an arduino on wifi... I made it on Visual Studio 2015 and it worked OK . If I started dubugging and connected to the arduino and then closed the form, it all worked fine... If I started debugging and never connected to the arduino, and closed the form , it would throw an exception...
I put in a try / catch to inform me of the error and then go ahead and close the form

I just opened this project in VS 2022 and the try / catch no longer works. why would that be ? ... seems that is the whole purpose of the try / catch.. to ignore exceptions that don't matter

VB.NET:
 Private Sub Form1_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
     Button3.Visible = True
     Button4.Visible = False
     Try
         client.Close()
     Catch ex As Exception
         'MsgBox(ex.Message)
         MsgBox("Form Closed... resources released")
     End Try
 End Sub

I get this exception:
System.NullReferenceException: 'Object reference not set to an instance of an object.'

When I get to the point of the form closing , I don't care that the client was never set to an instance, but the try / catch doesn't work

thank you
Realolman

client was Nothing.
 
NullReferenceException should break in debugger also within Try-Catch, depending on your exception settings. It will be caught when running without debugger.

You can check/change settings in menu Debug>Windows>Exception Settings. Search for 'null' and you'll find it under CLR exceptions.

About the code, if you expect possible null reference you don't need Try-Catch, you can check for it If client Is Nothing Then or ignore with null-conditional operator like this: client?.Close()
 
NullReferenceException should break in debugger also within Try-Catch, depending on your exception settings. It will be caught when running without debugger.

You can check/change settings in menu Debug>Windows>Exception Settings. Search for 'null' and you'll find it under CLR exceptions.

About the code, if you expect possible null reference you don't need Try-Catch, you can check for it If client Is Nothing Then or ignore with null-conditional operator like this: client?.Close()

VB.NET:
If client Is Nothing Then Exit Sub
client.Close()

worked fine... thank you very much... again,
Realolman
 
Back
Top