Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


vb.net how to do IF err.number = 2627 Then errMsg = "This student ID has exists! "

Posted on 2005-03-02
Medium Priority
Last Modified: 2008-01-09
Hi, every one.
Nice see you again.

I stuck at the exception handling part of my project. I feel VB.net has a lousy exception handling.
In vb6, i can catch exception , check the err.number and then use my own text to alert user.
For example:
if it is connection failed, then use my own error text like "Hi, brother turn on that blue PC. SQL server is inside."

If it is violation of primary key, then I can use "Dont register a tag with a existing ID. Please use a new ID."

Now in vb.net, they say i should  catch different specific exceptions and put my own error message.

There are two problem i met, first I cannot find what is that specific exception i wanna catch.
For example, I wanna catch the following error
Message      "Error: 2627: Violation of PRIMARY KEY constraint 'PK__TBL_TAG_INFO__505BE5AD'. Cannot insert duplicate key in object 'TBL_TAG_INFO'.
The statement has been terminated."

Who can tell me the specific exception?

Another Problem, i cannot decide which is narrow excpetion?

See my following code.

I put catch sqlexception before generic exception. Good, inside sqlexception , i can use err.num.
However some error like primary key Violation cannot be caught by sqlexception. It is caught by generic exception. i dont know the reason. maybe primary key Violation is not under sqlexception.
Then In generic exception, there is no err.number. What should i do?
I plan to trim the error number from the Ex.Message. But it seems quite funny. Shouldsome better method be there, right?

                  dim objDatabase as new clsDatabase("connectionStr")                  
                  iNoAffected = objDatabase.ExecSPNoReturn (strProcName, arrParams)
                  if iNoAffected = 1 then
                        RowTrackData(myRow,CType(Me.iTagID,Int32),sTagType, "Success","")                        
                  End If
            catch sqlEx as SqlException       
                        dim errMsg as String

                      if sqlEx.Number = 17
                              ' Server: Msg 17, Level 16, State 1
                              ' SQL Server does not exist or access denied
                              errMsg = "SQL Server does not exist or access denied"
                        elseif sqlEx.Number =  17142
                              ' Server: Msg 17142, Level 16, State 1
                              ' SQL Server has been paused. No new connection will be allowed
                              errMsg = "SQL Server has been paused. No new connection will be allowed"
                        elseif sqlEx.Number =  18456
                              ' Server: Msg 18456, Level 16, State 1
                              ' Login failed for user 'sa'
                              errMsg = " Login to database failed"
                        end if

                  RowTrackData(myRow, _
                                    CType(Me.iTagID,Int32), _
                                    sTagType, _
                                    "<font color='red'>Failed</font>", _
            catch ex as Exception       
                  dim errNum as Int64
                  errNum = System.Runtime.InteropServices.Marshal.GetHRForException(ex)
                  if errNum= -2146233088 then
                  else if errNum= -2146233088 then
                  End If
                  RowTrackData(myRow, _
                                    CType(Me.iTagID,Int32), _
                                    sTagType, _
                                    "<font color='red'>Failed</font>", _
                                    "This tag has been existing. Cannot register again.")
                  ' Create a DataView using the DataTable.
                  'myDataView = New DataView(myDataTable)                  
            end try
Question by:yangbin991
1 Comment
LVL 48

Accepted Solution

AlexFM earned 500 total points
ID: 13447257
General rule is to catch only exceptions which may be thrown by specific function. For example, SqlCommand.ExecuteNonQuery Method throws SqlException. When you use this function, only SqlException catch block should appear.
ExecSPNoReturn is your own function, and you need to catch all type of exceptions that it can throw. Every exception type has it's specific information, an it is not difficult to decide what to do with them.
Catching of general Exception is not recommended. .NET classes don't throw it, and our classes should not throw Exception as well. Catching of Exception hides program bugs which should be fixed when program is debugged.

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
Loops Section Overview
Suggested Courses

578 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