Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

C# vs VB6 Exception handling

Status
Not open for further replies.
Apr 11, 2002
193
IN
Hi,

I wanted to know the difference in Exception handling mechanism used by C# and VB6. Just wanted to know the process that C# follows. Like in C# its
try
{
}
catch()
{
}
finally
{
}

and in VB6 its on error goto error handler. I know that VB6 doesnt have finally. But how better or bad C# can be in terms of Exception handling as compared to VB6.

Regards,
Manish
 
The best thing that the modern exception handling in C# gets you is a built-in stack trace (you can see what methods you went through to get where the error happened). In VB6 you do the same thing by adding a on error goto handler in every single function and subroutine -- a lot more work, and sometimes because of coding mistakes you'll lose an error.

Chip H.


If you want to get the best response to a question, please check out FAQ222-2244 first
 
Hi Chip h,

I understand as C# is object oriented and so every exception has a class like the sqlexception class. This helps us to raise a specific error with a user defined message. We can also choose the hierarchy of the exceptions to be raised. But i dont know the concept of built-in trace. Can you please tell me how it works.

Regards,
Manish
 
Do a search in MSDN for "StackTrace".

Chip H.


If you want to get the best response to a question, please check out FAQ222-2244 first
 
Hey Chip,
It sounds like you're prasing the try...catch...finally way of dealing with exceptions, but I'm not sure why this is a better mechanism than the VB6 On Error statement. I'm coding in C# now and, back in my VB6 coding, I was able to resume execution after a given error occured. That was a very handy feature of VB6 that is missing in the structured exception handling mechanism, so I was actually unhappy with this. To date, I don't understand why it is better than the old way.

And something else:
ChipH said:
The best thing that the modern exception handling in C# gets you is a built-in stack trace [...]
I thought the stack trace had to do with the .NET framework, and had nothing to do with the try...catch...finally mechanism. Is this correct?


JC

 
>> back in my VB6 coding, I was able to resume execution after a given error occured. That was a very handy feature of VB6 that is missing in the structured exception handling mechanism, so I was actually unhappy with this. To date, I don't understand why it is better than the old way.

I'm not certain why you state that you can't resume execution after an error. It seems to me that you have much more flexibility in C#. Consider:

Code:
int MyInt1 = 0;
string MyInt2 = 15;
try {
   MyInt2 = MyInt2 / MyInt1; // Throws Divide by zero error
}
catch {
   //Do whatever... log the error, etc....
}
finally {
   //cleanup
}
 
//Execution resumes here

This keeps all of the error handling inline and localized rather than using the VB6 method of having to jump around everywhere. What scenario are you thinking of where you cannot resume?
 
Oops! Both variables in the above code should have been [bold]int[/bold]s. Sorry! ;-)
 
I meant resume execution back to the line where the error occurred, or to a line of your choice. This is very, very handy, yet is missing from C# exception handling.

Consider, for example, the following scenario: I have a VB6 database application (using Jet 4.0). Different users can add new records to a table. The primary key for each new record is computed from within my code so I have something that looks like this:
Code:
[COLOR=blue]Public Sub[/color] AddRecord()
[COLOR=green]   ' Get primary key value[/color]
   lPrimaryKey = GetNextKey()
[COLOR=green]   ' Save the record using a sql statement[/color]
   sSQL = "INSERT INTO MyTable ..."
[COLOR=green]   ' Execute the changes with connection[/color]
   cn.Execute(sSQL)
[COLOR=blue]End Sub[/color]
If two users (in two different computers) attempt to save a new record at, more or less, the same time, the function GetNextKey() may return the same key for both users (I have a series of rules for creating this key but this is not the issue). When this happens, one of the users won't be able to save his record because, obviously, the table does not allow duplicate values for the primary key.

This, in fact happens quite a few times during this data entry process, as records are constantly being created by different users. When this happens, I don't want to tell the user "Ooops!, your record could not be saved. Please try again later."

You see, what I do is, I inspect the error and if I think it was caused by two users trying to save at the same time, I resume execution to where the function GetNextKey() is. When GetNextKey() runs again, it will return the correct key and the user will be able to save his record. If in the mean time, another user is saving and the key is the same again, I just resume execution to GetNextKey() again. Now, the user is completely unaware of this. To him, he just saved a new record. Oh, and by the way, I also keep a count of how many times I've resumed for a record, so that I don't resume for ever. After a certain number of times, the user gets the message "An error occured and your record could not be saved. Please try again later."

So, you see, In Visual Basic 6, I could say Resume Next, Resume, Resume [to label]. These statements, when used wisely, proved to be very useful. With them, you don't have to know WHERE in code an error occured. By contrast, in C#, in order to resume execution to a place of your choice, you have to first know the block of code where the error might occur before hand and write loops or other form of code that will take care of the resuming business. Knowing which piece of code will throw an exception is not always so obvious as in the example I gave above.

So what do you say?

JC

Friends are angels who lift us to our feet when our wings have trouble remembering how to fly...
 
JC,

I am not quite familiar with VB6 error handling but here are few links that describes pros & cons of OnError...Goto Vs. Try..Catch..Finally

1. From MSDN

2. Another link taken from MSDN above post.

-Kris
 
Thought I'd jump in on the discussion, as I used to write in VB6 and now write in C#...I find that the try/catch/finally method of error handling is much more useful than the old On Error methods.

I know that try/catch method supports nesting, which can be very nice. It was my experience that in a given area of code (be it function, sub, whatever) in VB6 you could only handle an error in one location.

There is more structure, yet in some ways more flexibility with try/catch method. It was sometimes hard to follow error handling with On Error...the Resume Next was a simple way to just "ignore" an error. With the forced structure on try/catch, programmers won't disregard an unknown error as easily. As far as flexibility, I'm a fan of creating my own exceptions (Exception = Error). For example, if I had JCruz's AddRecord function, I would be able to throw my custom KeyExists exception. Whatever snippet of code I had calling KeyExists could handle that error spefically. If another error came up, I could easily handle it differently.
Simple Example (wouldn't really do it this way):
Code:
private void AddNewRecord_Click([i]click arguments[/i])
bool blnSuccessful = false; // stores whether record was added successfully
while (blnSuccessful == false)
{
   try
   {
       AddRecord();
       blnSuccessful = true;
   }
   catch(KeyExistsException err)
   {
       // Do whatever you want to do if Key already existed
   }
   catch(Exception err)
   {
       // Another error occurred. Maybe connectivity problem, whatever.
   }
}

Also, in my experience I find the flow of try/catch to be more logical. Normally, if an error occurs I want the block of code that's currently being processed to stop. Both methods of error handling do that. But I find that very often, there's some "clean-up" code you want to run no matter what. Maybe closing all your connections to a DB, whatever. Putting that in the "finally" clause allows me to make sure that it will happen no matter what...and I don't have to write it twice.

Well, I should probably get back to work. I feel there are many more advantages to try/catch that I haven't even touched on...but after having used both, I am very pleased with the try/catch method.

-Aaron
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top