Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Jul 28th, 2006, 10:29 AM   #11
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
Quote:
Originally Posted by lectricpharaoh
I agree with MBirchmeier. They are nice to have, and go a long way to writing robust code. However, the performance is usually much slower than simply checking a flag or return value, and as such, they shouldn't be used for most operations. For example, when opening a file, it seems nonsensical to throw an exception if the file cannot be opened; instead, return a success/failure code like the C standard library does.
I strongly disagree with this recommendation.

Firstly, the performance overhead would only make a significant difference if one were expecting exceptions to be thrown on a regular basis. If you throw exceptions only in exceptional circumstances (as the name "exceptions" suggests), then any performance degredation is going to be negligible at best.

Further, exceptions have several advantages over return values. From a structural point of view, they cleanly separate the concept of return values from errors and warnings. From a practical point of view, they automatically propagate up the stack until they are caught, so the programmer need only deal with the error once, rather than construct an elaborate chain of return values, or a singleton/global variable to hold error information. Finally, languages like Java throw compile errors at uncaught exceptions, preventing possible bugs.

In any unusual or exceptional circumstance, exceptions should be used. Return values should not, in my opinion, be used for anything other than returning valid data.
Arevos is offline   Reply With Quote
Old Jul 28th, 2006, 10:48 AM   #12
MBirchmeier
Hobbyist Programmer
 
Join Date: Oct 2005
Posts: 211
Rep Power: 4 MBirchmeier is on a distinguished road
Quote:
Originally Posted by Arevos
If you throw exceptions only in exceptional circumstances (as the name "exceptions" suggests), then any performance degredation is going to be negligible at best.
Yes, that's what I was trying to say, and I believe that's what pharoah was trying to say as well.

The problem is (especially when learning to use exceptions) there's a tendancy to overuse them, say in the example of opening a file, the following shouldn't be exceptions:

The file not existing
The file being locked
The file not being the format expected
Not being able to write to the file

The following could be exceptions:

The file dissappearing or being deleted after being opened
Outside failures in the middle of writing (eg. hard drive fills up)

I've seen too many instances of code where people use exceptions as flow control to see if a file exists. If it's writeable etc. If they truly are exceptional cases, by all means try/catch/finally them, however, if it's something that can easily be checked programatically then by all means do so.

-MBirchmeier

note: the performance loss of a try/catch is usually minimal compared with customer frustration at a program that crashes. It should be common practice to try/catch any code that might be expected to throw exceptions, but they should only be thrown when the outside envrionment does something unexpected, not because your program did something unexpected such as divide by 0, or try opening a file that doesn't exist.
MBirchmeier is offline   Reply With Quote
Old Jul 28th, 2006, 11:13 AM   #13
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
Quote:
Originally Posted by MBirchmeier
The problem is (especially when learning to use exceptions) there's a tendancy to overuse them, say in the example of opening a file, the following shouldn't be exceptions:

The file not existing
The file being locked
The file not being the format expected
Not being able to write to the file
Again, I disagree. When one writes some code to open a file, the usual expected result is that the file is opened correctly. Any other result should be cause an exception.

Now, if one were doing work with threads, then one might expect files to be found locked regularly, and because it is expected, one would probably have some function to check whether the file is locked rather than handle it via an exception. Likewise, if one wishes to write to a file that may not yet exist, then one may specify an option to create the file, if it doesn't already exist, rather than to handle it with exceptions.

But this only applies when the difficulty is a common and expected occurance. When the difficulty is unexpected, such as with your third example ("The file not being the format expected"), then you should certainly use an exception. Indeed, I'd go so far as to say it's bad practise not to use one.

The other factor to consider is the handling of unexpected events. If I have an application that accesses a file, and that file turns out to be in an invalid format, then it's logical that I report said error to the user. But since my program is clean and modular, I can't pollute my document opening function with GUI specific code. Likewise, because I happen to be using a statically typed language, I can't return an error message when a document is expected.

So I either have to wrap up the document in an error handling layer, or I have to record the error in a global variable that can be polled when necessary. In short, I have to create my own exception handling routines and reinvent the wheel. And reinvent it badly, as it happens, since neither solution has all the benefits that exceptions have.

Thus, in any case where non-standard behaviour occurs, exceptions are the best way to handle it.
Arevos is offline   Reply With Quote
Old Jul 28th, 2006, 11:34 AM   #14
MBirchmeier
Hobbyist Programmer
 
Join Date: Oct 2005
Posts: 211
Rep Power: 4 MBirchmeier is on a distinguished road
Ironically enough for the same reasons I tend to disagree.

For these types of problems, locked files, invalid formats, etc. They're generally something that's easy to check for. In my world the user entering filenames that might not exist, a text or XML not being of the expected format, or not having write access are all considered common occurances. It's just something that should be checked.

Programatically handling an error can be easily done with an error handler without breaking modular code. (Generally something I consider a utility anyway) You call your error utility to notify where and what type of error occured, (and the severity,(silent, log, popup to the user, critical))the error handler knows how to handle the GUI, (potentally even waiting for user input) and you can continue on with execution as normal.

Note @Arevos:

Googling for: When to use exceptions : comes up with a blog with a point of view similar to your own Blog Linky
Googling for : Proper use of exceptions: comes up with an article similar to my point of view Article Linky

They're both good reading, and might give everyone a better idea of what exceptions should be for.

-MBirchmeier
MBirchmeier is offline   Reply With Quote
Old Jul 28th, 2006, 1:06 PM   #15
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
Quote:
Originally Posted by MBirchmeier
Programatically handling an error can be easily done with an error handler without breaking modular code. (Generally something I consider a utility anyway) You call your error utility to notify where and what type of error occured, (and the severity,(silent, log, popup to the user, critical))the error handler knows how to handle the GUI, (potentally even waiting for user input) and you can continue on with execution as normal.
But what advantage does this have over exceptions? It seems like reinventing the wheel.

Whilst I can't think of any advantages to the above approach, I do think it suffers from three main disadvantages: it's nonstandard, doesn't support stack transversal, and lacks compile time checking in languages which have that.
Arevos is offline   Reply With Quote
Old Jul 28th, 2006, 1:57 PM   #16
MBirchmeier
Hobbyist Programmer
 
Join Date: Oct 2005
Posts: 211
Rep Power: 4 MBirchmeier is on a distinguished road
Quote:
Originally Posted by Arevos
I do think it suffers from three main disadvantages: it's nonstandard, doesn't support stack transversal, and lacks compile time checking in languages which have that.
Non-standard: I don't know quite what you mean by this. If by non-standard you mean it makes use of an error handling module I'd disagree, passing references of your error routine classes fits well within OOP standards. I can't think of any other standards it might be breaking.

No stack transversal: True, but raising an event can implement similar functionality, across not only the current thread, but others as well. One datasource might be updating one or more pages or controls, raising an event notifies all reliant parts what's going on, not just those on the direct stack.

Additionally I was taught that traversing a stack is a bad way to get things done unless it's absolutely necessary. If you're moving more than a layer off of the stack, expected closing methods or routines that should be finalized might not run if the coder of an intermediate layer hadn't planed for an exception.

Lacks compile time checking: I don't see how so. Can you give an example of this?

-MBirchmeier
MBirchmeier is offline   Reply With Quote
Old Jul 28th, 2006, 2:47 PM   #17
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
Quote:
Originally Posted by MBirchmeier
Non-standard: I don't know quite what you mean by this. If by non-standard you mean it makes use of an error handling module I'd disagree, passing references of your error routine classes fits well within OOP standards. I can't think of any other standards it might be breaking.
If I want to catch a custom exception in VB.NET (or, indeed any language that supports exceptions):
vbnet Syntax (Toggle Plain Text)
  1. Try
  2. SomeFunction("Foobar")
  3. Catch ex As FoobarException
  4. Console.WriteLine(ex.Message)
  5. Finally
  6. SomethingElse()
  7. End Try
The only custom error handling part is FoobarException. Everything else is standard and instantly recognisable. With a custom error handling system, there would be no standard components. This would make the code more difficult to read for those unfamiliar with the error handling system.

Quote:
Originally Posted by MBirchmeier
No stack transversal: True, but raising an event can implement similar functionality, across not only the current thread, but others as well. One datasource might be updating one or more pages or controls, raising an event notifies all reliant parts what's going on, not just those on the direct stack.
That is one advantage, but it's an advantage that integrates easily with the current exception handling model. Just add some class variables and a few synchronization control structures to the base exception class and you're done. The only advantage I can think of to a custom exception handling scheme is that it doesn't by default halt operation of the function, but most of the time you want to halt invalid operations, so it seems a sensible default to me.

Quote:
Originally Posted by MBirchmeier
Lacks compile time checking: I don't see how so. Can you give an example of this?
Neither VB.Net nor C# have checked exceptions, so I'll have to descend into Java, which does support this:
java Syntax (Toggle Plain Text)
  1. void foo() throws FoobarException {
  2. throw new FoobarException();
  3. }
  4.  
  5. void bar() {
  6. foo(); // Compile time error - FoobarException is not caught
  7. }
As the above code demonstrates, you have to explicitly catch an exception, or pass it up to the next level. An exception cannot be left uncaught (unless it inherits from RuntimeException). This theoretically ensures that all exceptions are handled - otherwise Java refuses to compile the program.
Arevos is offline   Reply With Quote
Old Jul 28th, 2006, 3:46 PM   #18
MBirchmeier
Hobbyist Programmer
 
Join Date: Oct 2005
Posts: 211
Rep Power: 4 MBirchmeier is on a distinguished road
Quote:
Originally Posted by Arevos
If I want to catch a custom exception in VB.NET (or, indeed any language that supports exceptions):
vbnet Syntax (Toggle Plain Text)
  1. Try
  2. SomeFunction("Foobar")
  3. Catch ex As FoobarException
  4. Console.WriteLine(ex.Message)
  5. Finally
  6. SomethingElse()
  7. End Try
A trivial point, .NET doesn't support Try/Catch/Finally clauses, only Try/Catch, or Try/finally. It's one shortcoming that I'd like to see them alter, I know there's functional ways around it, but oh well.

Quote:
The only custom error handling part is FoobarException. Everything else is standard and instantly recognisable. With a custom error handling system, there would be no standard components. This would make the code more difficult to read for those unfamiliar with the error handling system.
You keep mentioning standard components, for the purposes of errors/logging, how do you generally maintain unform messages and logging with this try/catch methodology? Generally we try to keep our programs in 4 seperate sections: a Data layer (data collection, base IO), a Logic layer(data manipulation), a UI layer(user input, display) , and a utilities layer (structures for base types, INI readers, logging/error handling, etc.) As a general rule all will have access to the Util layer, UI will see the Logic, and the Logic will see the data layer*. Using a try/catch (without the benefit of a custom error handler) an excpetion in the data layer would need to move to the Logic layer, then either continue moving up, or get re-thrown to the UI layer to effectively display the event. However, oftentimes execution in the Logic layer, should be unaffected by a problem in the data layer, rather the Logic layer notes the problem and moves on. Might an try/catch method be better for such cases, and if so should a custom error handler/logger be removed from this scenario?

Quote:
Neither VB.Net nor C# have checked exceptions, so I'll have to descend into Java
This point is one of your strongest, and now that I better understand what you mean I'll try to provide a better explination for my thoughts. In java this might be necessary because (and correct me if I'm wrong) you never leave the virtual machine of the java world, what occurs in java stays in java.

In .NET this isn't always the case. You can have external (and even non managed) code in the stack. If used to relying on exceptions, exceptions that pass through non-managed code can have unexpected results, yes good practice says that you should catch any exceptions before moving boundaries from managed to un-managed, but often times I've seen coders neglect this recommendation, either out of ignorance, or out of (usually undeserved) trust in the non-managed code.

-MBirchmeier

I know we're starting to drift a bit off topic (I hope no one minds because I think it's getting interresting) if we're too far off topic though perhaps we should move this to PMs

*: This level of seperation might seem excessive, but there's reasoning behind it. We do a lot of assembly line and Device related operations. Which means we get in data from a lot of different sources in a lot of different formats, (open ports, serial feeds, t/ftp, databases, snmp etc) however the data contains the same pertinant information. The Logic Layer is (usually) independant as possible, only relying on interface information from the data layer to collect the raw data, and manipulate it as necessary. The UI layer relies on interfaces from the logic layer, but different installations require different UI requirements. (the util provides cross layer utilities such as error handling, so that a problem in the DataLayer can provide notification in the UI layer if necessary, without needing to muck up the Logic Layer's execution.) This means that (hopefully) at a new installation we need to write data extracters to collect their data, possibly a custom UI depending on what they want, and the rest is gravy.
MBirchmeier is offline   Reply With Quote
Old Jul 28th, 2006, 4:53 PM   #19
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
Quote:
Originally Posted by MBirchmeier
A trivial point, .NET doesn't support Try/Catch/Finally clauses, only Try/Catch, or Try/finally. It's one shortcoming that I'd like to see them alter, I know there's functional ways around it, but oh well.
What are you talking about? .NET's supported Try/Catch/Finally since 1.0. Indeed, I've just tested a try/catch/finally in C#, and it compiles fine.

Quote:
Originally Posted by MBirchmeier
Using a try/catch (without the benefit of a custom error handler) an excpetion in the data layer would need to move to the Logic layer, then either continue moving up, or get re-thrown to the UI layer to effectively display the event. However, oftentimes execution in the Logic layer, should be unaffected by a problem in the data layer, rather the Logic layer notes the problem and moves on. Might an try/catch method be better for such cases, and if so should a custom error handler/logger be removed from this scenario?
In which case you're tying your error handling code to a fixed layered structure, whilst try-catch statements are independant of any third party library.

A more modular approach would be to catch the raised exceptions and wrap them up into an event system. This would decouple your error handling from your data layers entirely, whilst still allowing you to handle errors through globally distributed events.

The advantage with this approach, over the approach you prescribe, is that only the functions that have to be are tied into the framework. This allows one to detatch any method not specifically part of the layer framework you describe.

Quote:
Originally Posted by MBirchmeier
I know we're starting to drift a bit off topic (I hope no one minds because I think it's getting interresting) if we're too far off topic though perhaps we should move this to PMs
Since we're talking about the merits of try-catch statements, I think we're still on topic. If anyone disagrees, I have no particular objection to moving to PMs, though it would probably be more useful to continue this on the forums, as there's always the off chance someone else will find it useful.
Arevos is offline   Reply With Quote
Old Jul 28th, 2006, 5:26 PM   #20
MBirchmeier
Hobbyist Programmer
 
Join Date: Oct 2005
Posts: 211
Rep Power: 4 MBirchmeier is on a distinguished road
Quote:
Originally Posted by Arevos
What are you talking about? .NET's supported Try/Catch/Finally since 1.0. Indeed, I've just tested a try/catch/finally in C#, and it compiles fine.
hmm... I wonder what I was talking about It's working for me now too, we were having troubles with it at one point, I'll have to revisit that project briefly. I must be remembering something wrong. (I'll blame it on the fact that it's a friday)

Quote:
In which case you're tying your error handling code to a fixed layered structure, whilst try-catch statements are independant of any third party library.

A more modular approach would be to catch the raised exceptions and wrap them up into an event system. This would decouple your error handling from your data layers entirely, whilst still allowing you to handle errors through globally distributed events.
we currently do something like this for the exceptions that are thrown, but it we only do it with the exceptions that are truly critical. But even then in these events we generally poke our own error handler to ensure it gets logged properly.

Quote:
The advantage with this approach, over the approach you prescribe, is that only the functions that have to be are tied into the framework. This allows one to detatch any method not specifically part of the layer framework you describe.
Ours isn't coupled into any layer of the framework other than the utility layer, which mainly ensures utilities that will need to be implemented anyway (for loggers and such) Our error routines generally just piggy back on our logger routines anway.

-MBirchmeier
MBirchmeier is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
VBA-if statements Quagmire Visual Basic 3 Feb 17th, 2006 3:44 PM
Catch command line output SoniX Visual Basic .NET 1 Jan 22nd, 2006 7:25 AM
Try without catch JavaDummy Java 4 Jul 30th, 2005 5:20 PM
Multiple IF statements, perhaps? foxcity911 PHP 7 Jun 22nd, 2005 4:33 PM
Code annoyance, variables not available outside of if statements? Arla C# 15 May 24th, 2005 9:53 AM




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 7:37 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC