try catch and return statement in java class
In this java example, we will learn return and the use of exit(0) in the try-catch block.
We will use a simple java class and how it will execute.
Example :1
public class Mytry {
public static int test1() {
int i = 1;
try {
return i;
} finally {
i = 2;
System.out.println("i="+i);
}
}
public static int test2() {
int i = 1;
try {
System.exit(0);
return i;
} finally
{
i = 2;
System.out.println("m="+i);
}
}
public static void main(String[] args) {
System.out.println("Hello, World!");
int z= test1();
System.out.println("z="+z);
int k= test2();
System.out.println("k="+k);
}
}
Program output:---
Hello, World!
i=2
z=1
Example 2:-
public class Mytry {
public static int test1() {
int i = 1;
try {
return i;
} finally {
i = 2;
System.out.println("i="+i);
}
}
public static int test2() {
int i = 1;
try {
System.exit(0);
return i;
} finally
{
i = 2;
System.out.println("i="+i);
}
}
public static void main(String[] args) {
System.out.println("Hello, World!");
int k= test2();
/*** program terminates execution form here.
System.out.println("k="+k);
int z= test1();
System.out.println("z="+z);
}
}
Hello, World!
In the main() first, it calls test2() and try block
System.exit(0) terminates the execution. There for test1()
not able to call.
These examples show the output depends upon how you call
the methods.
No comments:
Add your comment