Finally:
The finally statement is used to specify the action to take if none of the previous catch statements specifically deals along with the condition. It is similar to the default category of a switch statement, finally is the big net which catches everything that falls out of the exception handling statement.
An Instance along with catch, try and finally
The given instance is the standard structure for Java exception handling, incorporating try, finally and catch,
try{
statement that produces an exception
}
catch(ExceptionType1 e) {
process exception type 1
}
catch(ExceptionType2 e) {
process exception type2
}
finally {
process all other exception types
}
By using try in exception handling try is used to notify Java in which a block of code might produce an exception and that a few processing of that exception will be done instantly following the try. A syntax of try is
try statement;
or
try {
statement (s)}
The statement try starts the try construct and is followed through a statement or block holding the code which may produce an exception. this code could consist of various statements, one or more of that might produce an exception.
If any one statement produce an exception and the remaining statements in the block are skipped an execution continues along with the first statement following the try construct, that must be a catch or finally statement. It is an important point to remember. It is a simple way to determine that block of code should be skipped if an error occurs. Here is an instance:
public class Mymain {
public static void main (String args[]) {
int[] myArray =new int[10];
try{
System.output.println("Before valid array assignment) ;
Myarray[0]=1;
System.output.println("Before valid array assignment);
MyArray[100]=1;
System.output.println("After array exception");
}
}
}
In this instance the array MyArray is created along with a length of 10. That is followed through a try statement which holds various statements. First, Third, and Fifth statements simply write trace messages to the screen. A Second statement holds a standard assignment statement which assigns the value 1 to array element 0. A Third statement also assigns an array, other than attempts to assign a value of 1 to element 100 of the array. Since the array is only 10 in size, this produces an ArrayIndexOutBounds exception.
Within tracing the execution of the block of code following the try statement, a first three statements are executed commonly. The Fourth statement, the invalid assignment, wills start to execute and then produce an exception that causes execution to continue at the end of the block, skipping a Fifth statement.
A Compilation error will result if you attempt to compile this code as it stands since any try statement must be followed instantly through one or more catch or finally statements. No other type of statement is permitted after the end of the try statement and before the first catch or finally statement.