Hi guys,
So I managed to get a book on Java! and I'm at a point where it's talking about try/catch/finally statements, from what I understand say I've got a java program and the user clicks on a button called "load recent save" .. the button click event would call a method called load_recent and have a try catch statement, within the try it will check say an ini file for the last known location, but now say the user deleted the file.. so the last known location would be incorrect and it would throw the exception java.io.FileNotFoundException, this is where I'd like to know what happens, say I catch the exception and popup a dialog allowing the user to browse for the file and also it will clear that location. Okay so I've handled the exception.. but now I'm wondering when the code block of the catch has finished running, does the try statement start over ? I'm kind of confused on how this works.
The other thing is, I get the impression that try catch can be entirely avoided by just coding properly. For example if a person divides 0 by 0 it'll throw some exception, but it'll only throw that exception because as a coder I didn't think hey instead of using try catch what I can do is prevent 0 from being divided by 0 in the first place. So my guess is that reason try catch exists is to avoid extra code. By extra code I mean without using try catch a dev has to add more code to prevent that from happening by checking which values and operators are being used. How ever if try catch is used then no extra code is read, only when an exception is thrown does the compiler look for the relevant catch exception.. does that make sense ?
So first question is when an exception is found, does the compiler move back to the try statement or carry on from the caught exception ? or carry on from where an exception was last caught ? the third possibility sounds about right.
And then the second question is, is try catch really useful when errors can be predicted and handled with code in the first place.
↧