Reputation: 745
I am just wondering what the Java VM does with a Try-Catch. How does it execute it?
My best guess is that it is like a Linux system which when installing something does a test run and if no errors are found asks the user if he/she wants to proceed. In the case of a Try-Catch does it do a test run and if all is OK implement it?
Upvotes: 4
Views: 14370
Reputation: 16302
It starts executing normally, w/o any checking. If any exception occurs, it will break out of the clause (like break
in a loop), and immediately execute the catch
, if no exception was found, it will skip the catch clause.
The finally
clause, insures that it will be called no matter if an exception was thrown, or not. A practical example would be reading from a file or network, and close the streams, no matter if an exception was thrown or not.
Upvotes: 0
Reputation: 882
The code which can give some unexpected result which the program can't handle is kept inside the try block,and to handle/catch the unexpected crashing of the program we use catch block.Where we declare type of Exception the code can throw
Eg:
int a;
try {
a=1/0;//program wil crash here
}catch(Exception e){
System.out.println("Division by zero ");//handling the crash here
}
Upvotes: 1
Reputation: 3876
It is much simpler than that - if any clause included in the try clause generates an error, the code in the catch clause (corresponding to that error - you can have multiple catch for a single try) will be executed. There is no way to know in advance if a particular clause will fail or not, only to try to recover after the error happens.
If you have ten clauses and the last one throws an error, the modifications performed by the first 9 will not be "reverted"!
Upvotes: 4
Reputation: 66677
try
{
//execute your code
}catch(Exception e)
{
//Log message
//IF you don't want to continue with the logic inside method, rethrow here.
}finally{
//Ir-respective of what the status is in above cases, execute this code.
}
//Continue with other logic in the method
.This is useful in cases where you want to determine part of your code need to be executed (or) not in exception case.
To understand more about how try-catch works in java read this tutorial.
Upvotes: 4