Hi there. Sorry about the last post (if ya missed it, don't worry about it I have a question. Again, I am working on some excercises for a class. I can't quite understand the book as well as I would like and wondered... Could anyone help explain how to use try, catch, and throw methods, and when to use them? We have a few different .java files and we had to make 4 new exceptions (via RuntimeException) One class (the one that is supposedly reusable) is meant to use try and catchs, while the other (for a particular bank) is meant to use throws. If anyone can explain that, or help me, just reply here or email me (Ore_CladDragon@yahoo.com). Also, if you wish, I can email/icq you the code (95kb zipped). Thanks in advance!
Cain An explanation of those concepts could be fairly long... Is there a partciular part of it your confused about? If you dont even know a question to ask (I've been there too so I know how it feels) check out the section on exceptions in the Java Tutorial.
Thanks, Dave. The site is defintely a good start (and I am reading some of it now). I guess it is hard to give a question because I am really just looking for a place to start (an example of sorts) I guess it would be easier to see my code and know what I am talking about. Anyway, for now, I will try to find it out via the tutorial. Thanks again!
You might also try looking at the Java Language specification with is available at java.sun.com. It has a pretty good explanation and some samples to boot. That, together with the examples in the tutorials should help you out.
The point of using a try catch block is more robust error handling for your Java application. Sensitive or error-prone code is placed within a try block. If an exception occurs within the try block AND the matching exception can be found in the correpsonding catch block, the thread of execution will jump from the line that has the offending code and immediately goes to the catch block and execute whatever's there. You can use the catch block to roll back whatever you've done to an initial setting, do some clean up or damage control, inform the user and gracefully exit, whatever. You can then proceed to do something else, and the client need not be any wiser as to what happened. If there is NO matching exception in a catch block, this exception will be thrown back to the calling method (main() in our example above) and the cycle repeats again. Is the calling method inside a try block? Is there a matching catch? etc. If the exception is still not caught it will be thrown further back, to whatever method called the calling method in the first place, and so on. If the calling method is main() itself and the exception is still not caught, it will be handled by the default exception handler. The application will terminate and a stack trace will be produced.
The throws keyword is used if you want to programmatically throw an exception.