What exactly does the try catch block do.
Even if there are no issues with the input strings , should they not be validated within the JVM rather than within the try block.
Also does my analogy with the If Else blocks hold.
A "try" encloses code which might suffer an error (expressed as an Exception) and a "catch" encloses code which ought to be executed if and only if that error occurs (ie, that Exception is thrown). If an Exception occurs part-way through a "try" then only part of the "try" is actually executed.
A "finally" encloses code which will be executed after a "try" and any associated "catch"es have completed.
And simple validation is probably better done without Exceptions. You might do well to throw an Exception if the validation fails, however.
If you know what exaclty needs to be checked then as you said you can use "if----else---" block.
If you don't know the exact condition like, "if you are trying to access a file, you are not sure whether the files is available in a location specified or not". In such a situation if you enclose the file access logic inside the try block it will throw an exception by entering the catch block, if the file object does not exists. At the same time if it is availbale it will run smoothly.
Joined: Mar 09, 2009
What I meant was that if an error of any sort occurs during runtime while alues are being put in, should the error not be handled outside the TRY block.
Well I really sounded incoherent because i never really had a good idea of I was talking about in the first plae.
Joined: Oct 13, 2005
If you use a Reader for inputting values, you will have to handle Exceptions because most of their methods declare IOException or FileNotFoundException, which are checked Exceptions.
If you use the parseXXX methods (eg Double#parseDouble()) it is worthwhile using a try-catch for the NumberFormatException they throw (an unchecked Exception), and you can do something similar for Scanne without using Exceptionsr; look at this thread.
Like the posts before mine have explained a Try-Catch block is used to handle exceptions that would otherwise cause your program to fail.
Example: If you were trying to get a number for the user and the user enters an 'a'. This would cause an exception to be thrown by the JVM, and your program would fail.
It's also a good practice with Try-Catch blocks to handle specific exceptions, however if you don't know the name of the exception or if there will be an exception you can use a generic exception that will catch all exceptions.
Hope this helps.
"If the facts don't fit the theory, get new facts" --Albert Einstein
I was reading the entire discussions and i think try catch help to avoid abnormal terminations of program.When we use try catch we know exact reason of exception or program faliure.Else Program abruptly terminates
As Hunter McMillen said
a Try-Catch block is used to handle exceptions that would otherwise cause your program to fail.