Page 345 - CITS - Computer Software Application -TT
P. 345
COMPUTER SOFTWARE APPLICATION - CITS
} // Terminates JVM as file is not available
finally {
System.out.println(“Exiting the program”);
}
}
}
Output:
Exception caught. Terminating JVM.
Explanation:
The piece of code above is trying to read a file and print a line from it if the file exists. If a file doesn’t exist, the
exception is raised and execution will go in catch block and code exits with System.exit(0) method in the catch
block.
• We know, finally block is executed every time irrespective of try-catch blocks are being executed or not. But,
in this case, the file is not present so JVM will check the catch block where System.exit(0) method is used that
terminates JVM and currently running the program.
• As the JVM is terminated in the catch block, JVM won’t be able to read the final block hence, the final block
will not be executed.
Exit a Java Method using Return
exit() method in java is the simplest way to terminate the program in abnormal conditions. There is one more way
to exit the java program using return keyword. return keyword completes execution of the method when used and
returns the value from the function. The return keyword can be used to exit any method when it doesn’t return
any value.
Let’s see this using an example:
public class SampleExitMethod2 {
public static void SubMethod(int num1, int num2) {
if (num2 > num1) return;
int answer = num1 - num2;
System.out.println(answer);
}
public static void main(String[] args) {
SubMethod(2, 5); // if condition is true
SubMethod(3, 2);
SubMethod(100, 20);
SubMethod(102, 110); // if condition is true
}
}
Output:
1
80
Explanation:
In the above program, Sub Method takes two arguments num1 and num2, subtracts num2 from num1 giving the
result in the answer variable. But it has one condition that states num2 should not be greater than num1, this
condition is implemented using if conditional block.
If this condition is true, it will execute if block which has a return statement. In this case, SubMethod is of void type
hence, return doesn’t return any value and in this way exits the function.
332
CITS : IT&ITES - Computer Software Application - Lesson 85 - 93