Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Vanadium
Jan 8, 2005

The code in a finally block gets executed whether an exception is thrown or not. This does neither apply to regular blocks nor to catch blocks, so this is important.

Adbot
ADBOT LOVES YOU

csammis
Aug 26, 2003

Mental Institution

dougdrums posted:

So I was :420: (not now, earlier) and programming and thinking about the finally statement. Is there any god drat reason for the finally statement? The only situation I see using finally in is if I didn't want to put a catch statement after a try which is a horrible practice anyways. And even if I did want to do that, couldn't I just use catch { } instead?

Sorry if I'm retarded and there actually is a good use for finally and I just never figured it out.

Edit: C#.

This construct exists in Java too (does C++ have it?), and any introductory text on either language will tell you exactly what finally is for. It's not a replacement for a catch.

http://neptune.netcomp.monash.edu.au/JavaHelp/howto/try_catch_finally.htm#whyFinally

dougdrums
Feb 25, 2005
CLIENT REQUESTED ELECTRONIC FUNDING RECEIPT (FUNDS NOW)
I didn't think about catch throwing the exception. When I took java my instructor straight out told us he had no clue what it was for. Thanks.

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

csammis posted:

This construct exists in Java too (does C++ have it?), and any introductory text on either language will tell you exactly what finally is for. It's not a replacement for a catch.

C++ doesn't have "finally" because you should be using RAII instead. :)

floWenoL
Oct 23, 2002

dougdrums posted:

I didn't think about catch throwing the exception. When I took java my instructor straight out told us he had no clue what it was for. Thanks.

finally has nothing to do with catch throwing an exception. You should brush up on exceptions and how they're used, as it seems you don't understand them.

Incoherence
May 22, 2004

POYO AND TEAR

dougdrums posted:

So I was :420: (not now, earlier) and programming and thinking about the finally statement. Is there any god drat reason for the finally statement? The only situation I see using finally in is if I didn't want to put a catch statement after a try which is a horrible practice anyways. And even if I did want to do that, couldn't I just use catch { } instead?

Sorry if I'm retarded and there actually is a good use for finally and I just never figured it out.

Edit: C#.
Imagine that you have some expensive resource, like a file or a database. You try to read from it; if it succeeds, great; if it fails, you need to close it then maybe go try something else. You could write this as follows:
code:
DatabaseConnection db = MakeDatabaseConnection();
try {
  DoSomeDBShit(db);
} catch (DBException e) {
  // complain to the user/calling code
} finally {
  db.CloseConnection();
}
Without finally, you have to duplicate the CloseConnection piece in the try and catch blocks.

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

dougdrums posted:

I didn't think about catch throwing the exception. When I took java my instructor straight out told us he had no clue what it was for. Thanks.

Then the Java you were taught is crippled, because finally is fundamental.

Pseudo-code, since it's been so long since I worked in Java:

code:
File f = new File("somefile", "r");
try
{
  String str = f.read(...);
  // do stuff with str
  return true;  // success!
}
catch (IOException e)
{
  // some problem occurred while reading from f; handle it
  return false;  // failure!
}
finally
{
  // whether you're returning true or false, close the file when you're done
  f.close();
}
The code in finally always gets called, so it's where you put clean-up code that always has to happen no matter whether exceptions are thrown or not.

Without finally, you'd have to write this in one of two ways:

code:
File f = new File("somefile", "r");
try
{
  String str = f.read(...);
  // do stuff with str
  f.close();
  return true;  // success!
}
catch (IOException e)
{
  // some problem occurred while reading from f; handle it
  f.close();  // <-- repeated code, not good!
  return false;  // failure!
}
In this case, it's just one line, but if you had more complicated things to clean up, or lots of different exceptions to catch, repeating the code would be very bad. It's really easy to forget to put "f.close" in the exception handler, which would mean if an exception happens your file stays open forever.

code:
bool result;
File f = new File("somefile", "r");
try
{
  String str = f.read(...);
  result = true;  // success!
}
catch (IOException e)
{
  // some problem occurred while reading from f; handle it
  result = false;  // failure!
}
f.close();
return result;
This is just clumsy and cumbersome, and breaks down as soon as you have more complicated control flow.

Actually, it just occurred to me that neither of these will work if you don't want to catch IOException - if your routine is supposed to throw exceptions to the parent, there's absolutely no way to safely clean up without the finally statement:

code:
File f = new File("somefile", "r");
String str = f.read(...);  // throwing an exception here means f.close is never called
f.close();
C++ doesn't "need" a finally statement because it doesn't have garbage collection, so thing's are guaranteed destroyed as soon as they go out of scope, not "whenever the system decides it needs some more memory". (But sometimes you have to jump through some hoops to make RAII work naturally when a finally statement would be easier - welcome to C++.)

code:
{
  File f("somefile", "r");
  try
  {
    String str = f.read(...);
    result = true;  // success!
  }
  catch (IOException e)
  {
    // some problem occurred while reading from f; handle it
    result = false;  // failure!
  }
  // f goes out of scope and gets destroyed, no matter how the routine exits
  // f's destructor calls close()
}
Someone who doesn't know what finally is for has no business teaching Java.

dougdrums
Feb 25, 2005
CLIENT REQUESTED ELECTRONIC FUNDING RECEIPT (FUNDS NOW)

floWenoL posted:

You should brush up on exceptions and how they're used, as it seems you don't understand them.

No kidding, that's why I asked. I started off with assembly and C so this is new to me. Chill with the programming e-peen.

JoeNotCharles posted:

Then the Java you were taught is crippled, because finally is fundamental.

Pseudo-code, since it's been so long since I worked in Java:

code

The code in finally always gets called, so it's where you put clean-up code that always has to happen no matter whether exceptions are thrown or not.

Without finally, you'd have to write this in one of two ways:

code

In this case, it's just one line, but if you had more complicated things to clean up, or lots of different exceptions to catch, repeating the code would be very bad. It's really easy to forget to put "f.close" in the exception handler, which would mean if an exception happens your file stays open forever.

code

This is just clumsy and cumbersome, and breaks down as soon as you have more complicated control flow.

Actually, it just occurred to me that neither of these will work if you don't want to catch IOException - if your routine is supposed to throw exceptions to the parent, there's absolutely no way to safely clean up without the finally statement:

code

C++ doesn't "need" a finally statement because it doesn't have garbage collection, so thing's are guaranteed destroyed as soon as they go out of scope, not "whenever the system decides it needs some more memory". (But sometimes you have to jump through some hoops to make RAII work naturally when a finally statement would be easier - welcome to C++.)

code

Someone who doesn't know what finally is for has no business teaching Java.

This made it really clear to me, thanks. I can think of a few places where I should have used it before. The guy that taught it was sorta in the same boat I was in. He does more low level programming and got stuck teaching java. I ended up learning java from my horrible textbook anyways.

dougdrums fucked around with this message at 07:45 on Mar 2, 2008

zootm
Aug 8, 2006

We used to be better friends.

csammis posted:

An empty list isn't null in Java, it's just empty. size() == 0.
It's usually completely irrelevant, but it looks a little nicer to use "list.isEmpty()" rather than "list.size() == 0".

Vanadium
Jan 8, 2005

It is also faster if your standard library implementor decides to implement .size() in O(n) :colbert:

csammis, C++/CLI has finally, by the way. :)

Allie
Jan 17, 2004

dougdrums posted:

So I was :420: (not now, earlier) and programming and thinking about the finally statement. Is there any god drat reason for the finally statement? The only situation I see using finally in is if I didn't want to put a catch statement after a try which is a horrible practice anyways. And even if I did want to do that, couldn't I just use catch { } instead?

Sorry if I'm retarded and there actually is a good use for finally and I just never figured it out.

Edit: C#.

It's used in Python for the same reasons other people stated:
code:
f = open('/dev/null')
try:
    # do some stuff
finally:
    f.close()
The finally block is always executed, regardless of where execution stopped in the try block (due to an exception, or returning).

Newer versions of Python have a nicer syntax for that:
code:
with open('/dev/null') as f:
    # do some stuff
No need for the explicitly finally/close, the with statement sets it up so f.__exit__ is always called, which simply calls close() (and this __enter__/__exit__ protocol can be adapted to other kinds of classes, like database cursors, thread locks, etc.)

more falafel please
Feb 26, 2005

forums poster

Milde posted:

No need for the explicitly finally/close, the with statement sets it up so f.__exit__ is always called, which simply calls close() (and this __enter__/__exit__ protocol can be adapted to other kinds of classes, like database cursors, thread locks, etc.)

That's kind of similar to RAII. I like Python more and more every day :)

csammis
Aug 26, 2003

Mental Institution

Milde posted:

Newer versions of Python have a nicer syntax for that:
code:
with open('/dev/null') as f:
    # do some stuff
No need for the explicitly finally/close, the with statement sets it up so f.__exit__ is always called, which simply calls close() (and this __enter__/__exit__ protocol can be adapted to other kinds of classes, like database cursors, thread locks, etc.)

For posterity, C# has this too in the using keyword:
code:
using(FileReader reader = new FileReader("C:\\myfile.exe"))
{
  // read read read
}
// When execution leaves the using block, the FileReader is closed and disposed of
The lock keyword works on the same principle.

Vanadium
Jan 8, 2005

Nice you see that you guys are almost catching up to C++, and your syntax is only minimally clumsier too!

Edit: They should codename C# 4.0 "playing catchup"

necrobobsledder
Mar 21, 2005
Lay down your soul to the gods rock 'n roll
Nap Ghost
I'm having to do some flow control based upon exceptions that come back in Java and am wondering if there's anything that can do the following more cleanly:

code:
Class c;
try {
  try {
    c = Class.forName(someclasspathA);
  } catch(ClassNotFoundException e) {
    c = Class.forName(someclasspathB);
  }
} catch (ClassNotFoundException e) {
  // no suitable classpath found, throw exception
}
I suppose trying to do a for loop like the following might be worth a shot:

code:
Class c;
for (String className : listOfClassNames) {
  if (c != null)
    break;
  try {
    c = Class.forName(className);
  } catch (ClassNotFoundException e) {
    // doesn't matter, blah
  }
}
if (c == null)
 throw new ExceptionOfDoom();
I'm trying to dynamically load classes at runtime and can't write a classloader :(

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.
I'd probably write a helper function:

code:
Class loadClass(String classPath)
{
  try
  {
    return Class.forName(classPath);
  }
  catch (ClassNotFoundException e)
  {
    return null;
  }
}

...

Class c = loadClass(someclasspathA);
if (c == null) c = loadClass(someclasspathB);
if (c == null) throw new ExceptionOfDoom();

Femtosecond
Aug 2, 2003

I have a bit of code that I'm working on, and it has a use of '&' that I've never seen before.

quote:

switch(rand()&3)

I've seen rand() % 3 used a million times before, but never the &. It's still giving me random numbers but it seems like it's doing something a bit different. What does this do?

YardKGnome
Jan 18, 2003
Grimey Drawer

Femtosecond posted:

I have a bit of code that I'm working on, and it has a use of '&' that I've never seen before.


I've seen rand() % 3 used a million times before, but never the &. It's still giving me random numbers but it seems like it's doing something a bit different. What does this do?

3 is 0011 in binary. & is the bit-wise and operator. Basically, its giving you a random number between 0 and 3 (inclusive). It is equivalent to "% 4"

very
Jan 25, 2005

I err on the side of handsome.

YardKGnome posted:

3 is 0011 in binary. & is the bit-wise and operator. Basically, its giving you a random number between 0 and 3 (inclusive). It is equivalent to "% 4"

That seems like a bad idea. Somebody is going to want to add another case, change the 3 to a 4, and now you have a bug.

YardKGnome
Jan 18, 2003
Grimey Drawer

very posted:

That seems like a bad idea. Somebody is going to want to add another case, change the 3 to a 4, and now you have a bug.

Yup. Seems like a pretty bad idea in general.

nbv4
Aug 21, 2002

by Duchess Gummybuns
I found a regular expression that seems to work when I test it out using this page: http://tools.netshiftmedia.com/regexlibrary/

But when I try to use it in my script, I'm getting an error. What am I doing wrong? Here is my code:

code:
var date_regex = (?=\d)^(?:(?!(?:10\D(?:0?[5-9]|1[0-4])\D(?:1582))|(?:0?9\D(?:0?[3-9]|1[0-3])\D(?:1752)))((?:0
?[13578]|1[02])|(?:0?[469]|11)(?!\/31)(?!-31)(?!\.31)|(?:0?2(?=.?(?:(?:29.(?!000[04]|(?:(?:1[^0-6]|[2468][^048]
|[3579][^26])00))(?:(?:(?:\d\d)(?:[02468][048]|[13579][26])(?!\x20BC))|(?:00(?:42|3[0369]|2[147]|1[258]|09)\x20
BC))))))|(?:0?2(?=.(?:(?:\d\D)|(?:[01]\d)|(?:2[0-8])))))(\/)(0?[1-9]|[12]\d|3[01])\2(?!0000)((?=(?:00(?:4[0-5]|
[0-3]?\d)\x20BC)|(?:\d{4}(?!\x20BC)))\d{4}(?:\x20BC)?)(?:$|(?=\x20\d)\x20))?((?:(?:0?[1-9]|1[012])(?::[0-5]\d){
0,2}(?:\x20[aApP][mM]))|(?:[01]\d|2[0-3])(?::[0-5]\d){1,2})?$;
	
	if ((date_regex.test(date)) || (date != ''))
	{
		alert('Invalid date');
		return false;
}

I'm getting a syntax error on the line where the regex variable is defined. I'm thinking I need to tell javascript that that big long line of text is a regex, because I think the error is caused by it thinking I'm forgetting quotation marks, or something. All the examples I've seen where regex's are used in javascript, they've just been bare like how I have it...

edit: long line broken up to prevent page breaking, the actual code does not have the line broken up

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh
You need to surround the regex with slashes, like you would in Perl.

Also why in god's name do you have a regex like that? I think when you have to worry about table breaking with a regex, you might want to look into writing a grammar to do whatever it is you're doing (possibly hard in Javascript unless there's a library for it). The benefit of a grammar is that it isn't write-only code. :)

Steampunk Mario
Aug 12, 2004

DIAGNOSIS ACQUIRED
I don't get it. What about that regex is unreadable? :raise:

edit: This is for an obfuscation contest, right?

N.Z.'s Champion
Jun 8, 2003

Yam Slacker
This is a bit of a weird question but what programming languages use :: (double colon) as part of their syntax and for what? Info on any language would be appreciated, particularly if the syntax has different uses. :)

(I've tried searching google but then google doesn't like non-alphanumeric searches)


The only ones I know are C++ and PHP,
C++ seems to use it for member functions and scope resolution. I don't understand how the compiler knows the difference -- how is that?
PHP uses it for public static functions

Are member functions the same as public static functions?

Update (the following day) sorry, I can't post an explanation yet but I will soon. I know this sounds weird but there's a good reason. I'll post in this thread with an update later (I suppose if you want to be notified send me a PM or an email on what-the-hell-is-the-double-colon-about@holloway.co.nz )

N.Z.'s Champion fucked around with this message at 00:17 on Mar 5, 2008

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender
Off the top of my head...

Miranda, Haskell, and that entire family of languages use it as the has-type operator. The Caml/OCaml family of languages use it as a cons, if I remember correctly. Perl and Ruby use it as a namespacing operator; probably lots of others in the nuevo-dynamic-language family.have a similar use. Several versions of make use the double-colon operator to construct prerequisite-dependent rules.

And you have got to explain why you're asking this question.

tef
May 30, 2004

-> some l-system crap ->
Can we get The book thread sticked? This is the second or third time we've had one now and it would be nice to keep one.

Aside: I'm tempted to write a FAQ but really the only frequent question is "WHat Language should I learn?"

Edit: I'm sure I meant to post this in the other sticked thread

tef fucked around with this message at 18:06 on Mar 4, 2008

tef
May 30, 2004

-> some l-system crap ->

N.Z.'s Champion posted:

This is a bit of a weird question but what programming languages use :: (double colon) as part of their syntax and for what? Info on any language would be appreciated, particularly if the syntax has different uses. :)

http://merd.sourceforge.net/pixel/language-study/syntax-across-languages.html

csammis
Aug 26, 2003

Mental Institution

tef posted:

Aside: I'm tempted to write a FAQ but really the only frequent question is "WHat Language should I learn?"

And the answer is "don't bother asking because you won't listen anyway" :smith:

tef
May 30, 2004

-> some l-system crap ->

csammis posted:

And the answer is "don't bother asking because you won't listen anyway" :smith:

"Who needs a project to learn a language when I can post a thread to ask moot questions" :smith::respek::smith:

tef fucked around with this message at 17:33 on Mar 4, 2008

nbv4
Aug 21, 2002

by Duchess Gummybuns

Avenging Dentist posted:

You need to surround the regex with slashes, like you would in Perl.

Also why in god's name do you have a regex like that? I think when you have to worry about table breaking with a regex, you might want to look into writing a grammar to do whatever it is you're doing (possibly hard in Javascript unless there's a library for it). The benefit of a grammar is that it isn't write-only code. :)

Why waste time writing a complicated function when you can just find a regex via google and plop it in?

edit: by the way, adding slashes doesn't fix it either. I'm now getting an "unterminated regular expression literal" error. I've now tried 3 or 4 different regex's I've found with Google, and they either give me a syntax error, or they parse fine, but return false every time. this is starting to piss me off.

nbv4 fucked around with this message at 18:43 on Mar 4, 2008

6174
Dec 4, 2004

nbv4 posted:

edit: by the way, adding backslashes doesn't fix it either.

Avenging Dentist didn't suggest adding backslashes. He suggested slashes, aka forward slashes.

6174
Dec 4, 2004

N.Z.'s Champion posted:

This is a bit of a weird question but what programming languages use :: (double colon) as part of their syntax and for what? Info on any language would be appreciated, particularly if the syntax has different uses. :)

Fortran 90/95 (and maybe 2003, but I'm not as familiar with it) uses it in variable declaration.
code:
      REAL(DOUBLE) :: DET 
This declares a variable "DET" as a floating point of size "DOUBLE".

nbv4
Aug 21, 2002

by Duchess Gummybuns

6174 posted:

Avenging Dentist didn't suggest adding backslashes. He suggested slashes, aka forward slashes.

gah, I have a habit of calling either back slashes or front slashes "backslashes". I tried adding front slashes and it gave me the "unterminated regular expression literal" error. Backslashes gave me a syntax error.

karuna
Oct 3, 2006
::Visual Basic::

How can i control the rate at which i change the properties of labels..
I'm trying to mimic a pump transferring water from one tank to another..
Each tank is made up of 10 tables.

At the form load, the right tank's labels all the visible = true and the left tank has visible = false...
I want to dynamically change the right tank's labels to visible = false and the left to true at X rate..

The problem I'm having is controlling the rate at which this happens... There are meant to be 5 different rates that the user can set.. rate 1 means it takes 10 seconds to change all the properties and rate 5, 2 seconds.

The other problem I'm having is that at the moment i have to directly state each label to change its properties..

Is there anyway i can say like
code:
Dim x As integer = 0

Do While (x < 10)
 lblLeftx.Visible = true
 lblRightx.Visible = false
 x+= 1
loop
What other ways can i go about solving this? I'm very new to vb..

Thanks in advance.

very
Jan 25, 2005

I err on the side of handsome.

karuna posted:

::Visual Basic::

Thanks in advance.

If you want something to take a certain amount of time, you can use a timer. Timers have a tick function that gets called every specific amount of time, and you can turn them on and off and specify the amount of time etc.

In order to be able to refer to your controls by number, you need to make a control array.

I don't know the specifics of how to implement these in VB, and it probably depends on what version of VB you are using, but at least you know what to google for now.

karuna
Oct 3, 2006
Just did a quick search there and it seems control arrays are no longer supported, I'm using visual basic 2008 express edition..
Would you know of any other way i can refer to the labels with a variable?

Cheers

csammis
Aug 26, 2003

Mental Institution

karuna posted:

Just did a quick search there and it seems control arrays are no longer supported, I'm using visual basic 2008 express edition..
Would you know of any other way i can refer to the labels with a variable?

Cheers

VB 2008 is .NET, please refer to the .NET Questions Megathread. You may be able to use reflection to access the labels.

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

nbv4 posted:

gah, I have a habit of calling either back slashes or front slashes "backslashes". I tried adding front slashes and it gave me the "unterminated regular expression literal" error. Backslashes gave me a syntax error.

It works fine for me. You're doing the following right?
code:
var date_regex = /[i]blahblahblahblah[/i]/;
Also, is there any particular reason you're using a regex that's checking to see if the date is after October 14, 1582 (i.e. is a Gregorian date)? It's doing some other equally strange stuff too. (EDIT: looks like the other strange stuff is to allow for the multiple instances that nations switched from Julian to Gregorian date systems.) Why not just use a simple regex to extract the pieces of the date, create a new Date object and make sure it's valid?

Avenging Dentist fucked around with this message at 20:59 on Mar 4, 2008

nbv4
Aug 21, 2002

by Duchess Gummybuns

Avenging Dentist posted:

It works fine for me. You're doing the following right?
code:
var date_regex = /[i]blahblahblahblah[/i]/;



this is the exact error I get. And here is the top few lines of my code:

code:
function validate_new_entry_form() 
{

	var route = document.forms[0].route.value;
	var total = document.forms[0].total.value;
	var date = document.forms[0].date.value;
	
	var day_landings = document.forms[0].day_landings.value;
	
	var night_landings = document.forms[0].night_landings.value;
	
	var date_regex = /(?=\d)^(?:(?!(?:10\D(?:0?[5-9]|1[0-4])\D(?:1582))|(?:0?9\D(?:0?[3-9]|1[0-3])\D(?:1752)))((?:0
?[13578]|1[02])|(?:0?[469]|11)(?!\/31)(?!-31)(?!\.31)|(?:0?2(?=.?(?:(?:29.(?!000[04]|(?:(?:1[^0-6]|[2468][^048]
|[3579][^26])00))(?:(?:(?:\d\d)(?:[02468][048]|[13579][26])(?!\x20BC))|(?:00(?:42|3[0369]|2[147]|1[258]|09)\x20
BC))))))|(?:0?2(?=.(?:(?:\d\D)|(?:[01]\d)|(?:2[0-8])))))(\/)(0?[1-9]|[12]\d|3[01])\2(?!0000)((?=(?:00(?:4[0-5]|
[0-3]?\d)\x20BC)|(?:\d{4}(?!\x20BC)))\d{4}(?:\x20BC)?)(?:$|(?=\x20\d)\x20))?((?:(?:0?[1-9]|1[012])(?::[0-5]\d){
0,2}(?:\x20[aApP][mM]))|(?:[01]\d|2[0-3])(?::[0-5]\d){1,2})?$/
	
	if (total <= 0)
	{
		alert('Total time can not be 0');
		return false;
	}
	else if (!date_regex.test(date))
	{
		alert('Invalid date');
		return false;
	}

Adbot
ADBOT LOVES YOU

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh
Get rid of the newlines in the regex (obviously don't do this in the post :)).

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply