Just learning about exception handling. I'm wondering if exception handling should be used for all programming situations?
any help will be greatly appreciated
You might try http://onjava.com/pub/a/onjava/2003/11/19/exceptions.html for 'best practices for exception handling'. I haven't read it closely, but it seems to be a thorough treatment and not obviously wrong.
Explicit exception handling should be used where exceptions are expected.
To be more specific, if the consequences of an exception matter to your program, you should handle them. If they don't matter, feel free to ignore them.
A simple program that adds two numbers doesn't really need exception handling, as long as the input can be ensured to be correct. Most applications aren't that simple though, so exception handling is used.
The answer is yes, in production environments. Exceptions should be handled where possible, or otherwise thrown to the caller. You should then also always provide an exception handler around all entry points to you program, that is main
methods and/or thread boundaries, where you should catch all unhandled exceptions and log them or in some way.
For prototypes, you can ignore most handling that is not of interest to your program logic.
The thing to remember about exception handling is that it is VERY expensive. Using exceptions to test for conditions is usually the wrong way to go. Must better is to test.
Write the logic both way and you will see the performance difference.
That said, exceptions need to be handled (just don't use them when they are not needed).
Exception handling is a predominantly Object Oriented Programming paradigm. Functional programming uses return codes. The issue was that people often ignored these.
E.G. Malloc may(and probably will as of this writing) return null if you ask for 10GB of memory.
Where as with Exceptions if you don't handle them your program crashes right then and there, not later when you continue on thinking the world is a happy place, but really your house is on fire ( -4311 )
精彩评论