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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Newbie 2 C# (VB programmer)... Try-Catch-Finally? 3

Status
Not open for further replies.

CubeE101

Programmer
Nov 19, 2002
1,492
0
0
US
Sorry for the 'dumb question', but I have been coding in VB for the last 5 years or so and Basic in general (GWBASIC, QBASIC, etc...) for over 10 years...

I have done some C/C++ coding, though I never really got into it, since most of the stuff I need I can do in VB...

But in C# (and I believe in VB.Net?) I see this Try-Catch-Finally block everywhere, that I have never seen before...

Can someone give me a quick run through of what you would use it for and how it works...?

Is it simmilar to a switch (or select case) statement?

Or is it for error handling, or what?

Thanks,
Josh

Have Fun, Be Young... Code BASIC
-Josh
cubee101.gif


PROGRAMMER: (n) Red-eyed, mumbling mammal capable of conversing with inanimate objects.
 
It's the .net approach to error handling.
Try: the mainstream logic
Catch: where you 'goto' when something goes wrong
Finally: do this stuff *always*, even if something goes wrong.

Using Instant C# (the vb.net to c# converter), here's an example of old vb6-style error handling in vb.net and followed by the equivalent C# try/catch code:

VB.NET:
Public Sub UnstructuredErrorHandlingExampleOne()

On Error GoTo ErrorHandler

'... <main logic>

On Error Resume Next 'this won't be converted

'... <more main logic>

'turn off error handling:
On Error GoTo 0

'... <more main logic>

CleanUp:
'... <cleanup code>
Exit Sub

ErrorHandler:
'... <error handling code>
If FirstSwitch Then
Resume 'this won't be converted
Else
'test alternative ways of getting to the cleanup block:
If SecondSwitch Then
Resume CleanUp
Else
GoTo CleanUp
End If
End If

End Sub

C#:
public void UnstructuredErrorHandlingExampleOne()
{
string ActiveErrorHandler = "";
try
{

// On Error GoTo ErrorHandler
ActiveErrorHandler = "ErrorHandler";

//... <main logic>

//INSTANT C# TODO TASK: The 'On Error Resume Next' statement is not converted by Instant C#:
On Error Resume Next //this won't be converted

//... <more main logic>

//turn off error handling:
// On Error GoTo 0
ActiveErrorHandler = "";

//... <more main logic>

CleanUp:
//... <cleanup code>
return;

}

catch
{
if (ActiveErrorHandler == "ErrorHandler")
{
//... <error handling code>
if (FirstSwitch)
{
//INSTANT C# TODO TASK: The simple 'Resume' statement is not converted by Instant C#:
Resume //this won't be converted
}
else
{
//test alternative ways of getting to the cleanup block:
if (SecondSwitch)
{
goto CleanUp;
}
else
{
goto CleanUp;
}
}

}
}
}
 
RhymesWithOrange,
I personally think there's less flexibility with the new try...catch...finally approach, yet everyone else seems to think the opposite. What are your thoughts about it?

JC


Friends are angels who lift us to our feet when our wings have trouble remembering how to fly...
 
So it is Error handling...

Does it work the same way in Java/javascript?

I found this example on another site:

Code:
//Any division by zero that occurs when executing the
//try block will result in execution of the catch block.
//Once either block completes, execution continues
//at the statement after the catch block.
try
{
   result = numerator / denominator;
   validResult = true;
}
catch (ArithmeticException e)
{
   validResult = false;
}

And so would this be the equivalent of a resume next?

Code:
try {document.all('nameRow').style.display = 'none';} catch (err) {}
(I think this is java too...)

Have Fun, Be Young... Code BASIC
-Josh
cubee101.gif


PROGRAMMER: (n) Red-eyed, mumbling mammal capable of conversing with inanimate objects.
 
You won't need a resume next. Take this code in VB 6. It is quite evident that this will cause an error in the second iteration, and that is is handled:

Code:
Private Sub TryLoop()
    On Error GoTo err_handler
    Dim i As Integer
    Dim ary(3) As Integer
    ary(0) = 1
    ary(1) = 0
    ary(2) = 2
    
    For i = 0 To 3
        MsgBox 5 / ary(i)
    Next
    
err_handler:
    Resume Next
End Sub

In C# or VB.Net (I'll use VB.Net as it is easier to modify to appear as the VB 6 code), you don't need a Resume Next, because of where you can place your error handling:

Code:
Private Sub Command1_Click()
    Dim i As Integer
    Dim ary(3) As Integer
    ary(0) = 1
    ary(1) = 0
    ary(2) = 2
    
    For i = 0 To 3
        Try
             MsgBox 5 / ary(i)
        Catch
        End Try
    Next
End Sub

In both circumstances, the code attemps to display 3 message boxes. I cannot do that, because it encounters a divide by zero error like your example. But the .Net example handles the error with code written inside the loop.
 
Thanks Guys,
I think I get it now...

So you can handle the errors in the same area they occur instead of jumping all over the place, and you can have multiple error handling routines in a single function.

Can you embed Try blocks in each other? (though I'm not sure why you would want to, but, you never know...)
Code:
Try
  MsgBox 5 / ary(i)
Catch
  Try
    MsgBox 5 / ary2(i)
  Catch
  End Try
End Try

Also, is the Catch required? or can you simply say:
Code:
Try
  MsgBox 5 / ary(i)
End Try


Have Fun, Be Young... Code BASIC
-Josh
cubee101.gif


PROGRAMMER: (n) Red-eyed, mumbling mammal capable of conversing with inanimate objects.
 
Personally, I don't see Try/Catch as a huge improvement, although I like exceptions better than meaningless error numbers.

Contrary to what someone posted here, there is no Try/Catch equivalent to "Resume Next". To ignore the exception in the Catch block, you're not resuming at the line following where the exception occurred. The only way to do this would be to increment a line number counter and then use a (shudder) "goto" to go back to resume at that line indicated by the latest value of the counter. YUK !!
 
Well from the way it looks, like RiverGuy mentioned, you don't need Resume Next...

In VB6, there were 2 ways that you could use resume next...
1...
Code:
On Error Resume Next
X = 5 / 0
MsgBox "No Corrective Handling Occured"

And 2...
Code:
On Error Goto FixIt
Y = 5 / 0
MsgBox "Y was changed to " & Y
Exit Sub

FixIt:
Y = 5
Resume Next

Where as Resume, by itself, could cause an infinite error loop, because y would constantly = 5 / 0

So, correct me if I'm wrong, but if used correctly this statement is essentially a replacement for resume next, and never as resume by itself...

so the .Net code for the above would look like this...?
1...
Code:
Try
  X = 5 / 0
Catch
End Try
MsgBox "No Corrective Handling Occured"

And 2...
Code:
Try
  Y = 5 / 0
Catch
  Y = 5
End Try
MsgBox "Y was changed to " & Y

But I still don't really see the use for Finally...???

Or does that just suppress error handling and continue, whether an error was raised or not...?

Have Fun, Be Young... Code BASIC
-Josh
cubee101.gif


PROGRAMMER: (n) Red-eyed, mumbling mammal capable of conversing with inanimate objects.
 
OK...

Looking at an example on MSDN...
Code:
// try-finally
using System;
public class TestTryFinally 
{
   public static void Main() 
   {
      int i = 123;
      string s = "Some string";
      object o = s;

      try 
      {
         // Invalid conversion; o contains a string not an int
         i = (int) o;   
      }

      finally 
      {
         Console.Write("i = {0}", i);
      }         
   }
}

Shows to have the following result:
i = 123

so it appears that the value of (i) did not change from the initial value assigned to it...

So Would this be any different if you wrote it like this...?
Code:
// try-finally
using System;
public class TestTryFinally 
{
   public static void Main() 
   {
      int i = 123;
      string s = "Some string";
      object o = s;

      try 
      {
         // Invalid conversion; o contains a string not an int
         i = (int) o;   
      }
      [b]Console.Write("i = {0}", i);[/b]
   }
}

Without the finally statement?

Also, what is the {0} for in Console.Write("i = {0}", i);

could you use it like this...?
Code:
int i = 123;
string s = "i = ";
Console.Write("{1}{0}", i, s);

Thanks Again,
Josh

Have Fun, Be Young... Code BASIC
-Josh
cubee101.gif


PROGRAMMER: (n) Red-eyed, mumbling mammal capable of conversing with inanimate objects.
 
Well, you'd have to have Try/Catch around every line of code in order to reproduce the functionality of Resume Next. I didn't think of that when I said the only option was to have a line counter and goto's, but even so you wouldn't want to have Try/Catch around every line.

The 'trick' of the Resume Next is that you could have a few dozen lines of code, and get back to the next line after an error was triggered. Personally, I think this is very sloppy since it's just a bunch of goto crap.

 
Well, you'd have to have Try/Catch around every line of code in order to reproduce the functionality of Resume Next.

Ahh, I see your point...

But you would only need to put it around code that could cause problems...

So if you had 5 areas in a sub that could potentially cause problems... and you only wanted to handle one of them, and ignore the errors of the others, you could set them up individually instead of wrapping them all under one resume next statement.

So far, the only time that I even use error handling is for dialog boxes that raise errors when you cancel...

So, for what I do this looks like it will work out better anyways...
I supose it would look something like this:
Code:
Try
  Dialog1.ShowOpen
Catch
  Exit Sub
End Try

I guess I'll see when I start using it more...

Thanks for the feedback,
Josh

Have Fun, Be Young... Code BASIC
-Josh
cubee101.gif


PROGRAMMER: (n) Red-eyed, mumbling mammal capable of conversing with inanimate objects.
 
Josh,
Regarding {0} ...
This is simply an easy way to print literal strings and variables together. {X} is just an indexed place holder for variables in a string. For example, in VB you would print something like this:
Code:
Console.WriteLine("Hi, my name is " & name & " and I live at " & address & ".");
where name and address are variables.

Using the curly brackets syntax, you would do:
Code:
Console.WriteLine("Hi, my name is {0} and I live at {1}.", name, address);
What the runtime does is it replaces the {0} with the variabes that you add after the literal string and it does it in the order in which they appear (starting with index 0). Thus {0} is replaced with name (because name is the first variable) and {1} is replaced with address (because it is the second variable).


Regarding finally...
This keyword is used (in error-handling) to denote a piece of code that you want to execute regarless of what happens. This is the place where you would dispose of resources you might be using, such as open files or connections. Why wouldn't you dispose of resources in a try block? Because the try block doesn't execute completely when an exception is thrown. Why wouldn't you put it in a catch block? Because the catch block doesn't get executed at all if no exception is thrown. Why wouldn't you put in both the try and the catch blocks? Because that would be a bad programming practice. Why don't you just ignore disposing of resources altogether? Because other programmers might want to beat you up if you did that :). Thus, you use the finally block!

Hope this helps!

JC

Friends are angels who lift us to our feet when our wings have trouble remembering how to fly...
 
myself said:
This keyword is used (in error-handling) to denote a piece of code that you want to execute regarless of what happens.
By "regardless of what happens" I meant whether an exception is thrown or not!


JC

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

JC, I played with the {x} a little when I got home last night and tried this (VB.Net):
Dim X As Integer = 5
Dim Y As Integer = 3
Console.WriteLine("Hello World {1} {0}", X, Y)


And it printed this...
Hello World 3 5

So that pretty much answered my question...

But I'll give you a star for your detailed explaination to be fair (and taking the time to answer my Dumb Questions ;-))

This .Net stuff takes a little getting used to...

So are VC# and VB.Net basically the same except for the way you write your blocks, and syntax structure?

What I mean buy this is, are they basically the same language, but each having a style that resembles the target developers previous language preference (VB or VC++)

such as:
VB.Net:
Code:
Try
Catch
Finally
End Try

VC#
Code:
Try{}
Catch{}
Finally{}

In other words, do they use all the same functions, controlls, and objects?

Or are there things that you can do in one but not the other?

Have Fun, Be Young... Code BASIC
-Josh
cubee101.gif


PROGRAMMER: (n) Red-eyed, mumbling mammal capable of conversing with inanimate objects.
 
Josh,
I wouldn't say they are the same language but that you could pretty much accomplish the same thing with both. One language has very little or no advantage over the other.

It is true that VB.NET does not support operator overloading (that is, overloading the behaviour of operators such as + - * /, so that they could be used with your own objects) but that will be history in Whidbey. Also, Visual Basic is a bit less capable than C# in terms of pointers.

In terms of exception handling, though, you could use both methods in VB.NET - that is, the old On Error statement as well as the new Try-Catch-Finally way. In C# you can only use the try-catch-finally method. I also heard that IntelliSense works better in Visual Basic than in C#.

Aside from that, though, C# and VB.NET are 100% equally capable. The reason for this is that in .NET, most the functionality is moved from the language to the .NET Framenwork itself.
FrancescoBalena said:
For example, the .NET Framework includes classes for opening, reading, and writing text and binary files, so there is no point in having that functionality embedded in programming languages. Another example: a portion of the .NET Framework named Windows Forms offers classes that can create windows and controls. (You can think of this portion as the heir of forms in Visual Basic 6.) All .NET languages can use these classes and therefore all languages have the same capabilities in creating applications with a rich user interface, without having to resort to low-level, advanced techniques such as subclassing.

Note: The above quote was taken from the book Programming Visual Basic .NET from Microsoft Press (2002) by Francesco Balena. (page 12)

One last thing: I'm not sure if you're aware of this but you can create VB/C# .NET applications using a simple text editor such as notepad because both the VB and the C# compilers belong to the .NET Framework. Thus, the bottom line is that in .NET (as Balena would say), All languages are born equal.

Hope this helps!

JC

Friends are angels who lift us to our feet when our wings have trouble remembering how to fly...
 
Yeah, actually, I am using the .Net Framework SDK (free dowload from MS) with an open source free IDE called #Develop (SharpDevelop)

I believe it can be found at...

So far I like it, the editor is VERY close (if not identical) to the MS original...

------------

And, don't both languages VC# & VB.Net both create IL code and use a JIT compiler (or something), so in the end do they actually use the same compiler (JIT)?

I guess it just seemed like VB.Net had more VC++ stuff in it than VB6 did...
And VC# has some stuff more similar to VB than VC++6

Have Fun, Be Young... Code BASIC
-Josh
cubee101.gif


PROGRAMMER: (n) Red-eyed, mumbling mammal capable of conversing with inanimate objects.
 
Josh,
At home, I use SharpDevelop as well. At work I use VS.NET. SharpDevelop might look like VS.NET but in terms of functionality it doesn't come close. Of course, it's still in beta mode so hopefully it will be improved. Its performance is acceptable, though.

JC

Friends are angels who lift us to our feet when our wings have trouble remembering how to fly...
 
And, don't both languages VC# & VB.Net both create IL code and use a JIT compiler (or something), so in the end do they actually use the same compiler (JIT)?

They both create the same MSIL code. So the JIT compiler is used on the MSIL code.


I guess it just seemed like VB.Net had more VC++ stuff in it than VB6 did...
And VC# has some stuff more similar to VB than VC++6

The OO conecpts in .Net are by far worth the migration from VB in and of itself. Say for example, you decide that you want a bunch of GroupBox (formally Frames) controls. But you want a logo or icon on each of them. Well, in VB6, you would either just remember to place them in your Frames each time, or you would create a UserControl and expose all of the frame's properties, and add the picture. You would also create the UserControl so that when it is resized, the frame it contains is resized as well. So you could have a lot of coding to do just to make some custom Frames with pictures. In .Net, you simply create a class that inherites from GroupBox. You start out with an empty class declaration. You add any extra properties you might need. You could just have it draw the picture on the OnPaint event of your inherited class. You have much less code.

Forms are exactly the same. When you create a form, it is just a class that Inherits from Form.

Another example would be a custom TextBox. Say you wanted the option of the Font being different when the TextBox had the focus. Well in VB 6, you could create a bunch of code for each TextBox that changes the fonts when the TextBoxes lose and gain focus. If you added a new TextBox,you would have to add additional code. In .Net, you can Inherit from TextBox, and add an "AlternateFont" property. You code in the Inherited class to switch fonts on gaining and losing focus. You only code it once and reuse it over and over.
 
I agree RiverGuy - that inheritance stuff is soooo delicious!

JC

Friends are angels who lift us to our feet when our wings have trouble remembering how to fly...
 
JCruz063 said:
At home, I use SharpDevelop as well. At work I use VS.NET. SharpDevelop might look like VS.NET but in terms of functionality it doesn't come close. Of course, it's still in beta mode so hopefully it will be improved. Its performance is acceptable, though.

Yeah, I'm pending final aproval to upgrade at work... (I think my manager is on vacation or something)
It sucks when you have to wait for someone to push a button to get a license, but I guess that's business... (though it's even worse when you know that the Disks to install it (pending a license) are waiting right down the hall :))

I figured there would be some features left out, since Microsoft always keeps a few tricks up their sleeve.

So is the IDE in VS.NET really that much better than #develop?

Also, #Develop is open source (if I'm not mistaking) so I suppose you could download the source and improve it yourself if you were inclined to do so... That's the way Open Source generally works right? You just have to share the improvements with the Community and open public...

O-Well...
Thanks For The Tips everyone,

Happy Coding,
-Josh

Have Fun, Be Young... Code BASIC
-Josh
cubee101.gif


PROGRAMMER: (n) Red-eyed, mumbling mammal capable of conversing with inanimate objects.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top