Hello folks , can anyone explain how we can use a try with a finally and still the code compiles and gives the output.
As far as i understand we can never give a try without a catch , coz that is the entire point of exception handling , if we are not handling the exception the compiler should give an error.
In Java we can write try with out catch also, but at that time we must use finally.
If you are not using catch block with try, at that time if any exceptions are raised progaram, JVM will stop excuting remaining statements, but it executes finally block.
Joined: Apr 23, 2010
Refer the following code.
First run the below program as it is and change the value 0 to some positive integer.
yeah i tried to run the run the code it runs displaying the messages in the try block throws the exception , how do i then expect my application to behave properly ie how can my application then work when some exception is thrown , wont the application terminate or give some error.
how can my application then work when some exception is thrown , wont the application terminate or give some error.
That depends on what the application is doing. In the example code, the value of "x" isn't used for anything, so it doesn't matter than an exception was thrown during calculating it. Generally, a catch block either needs to put things into a state where the application can keep running, or it needs to re-throw the exception (or return an error code) for the calling method to handle.
The examples we've seen so far aren't very realistic; there's no reason why you'd ever write code like the above. But imagine a routine like this:
This routine opens a file, converts each line to an int, and returns the sum of the ints. It can fail in a number of ways: there can be an IOException while reading or closing the file, and there can be NumberFormatExceptions if the data is malformed. Whatever code calls this method definitely should catch those exceptions. But this routine just throws them to report the problem. But even if the data is malformed, the file has to be closed -- not closing files you read is always a bad thing. So we use try/finally so that we always close the file, even if the parseInt() or readLine() throws an exception.