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);

     

     

 }

}


Program output :

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. 






try catch and return statement in java class   try catch and  return statement  in java class Reviewed by Mukesh Jha on 10:03 PM Rating: 5

1 comment:


  1. Ein Cybersecurity-Spezialist ist nicht nur ein Techniker, sondern auch ein Detektiv. Die Fähigkeit zur SIEM-Analyse (Security Information and Event Management) ermöglicht es, Bedrohungen frühzeitig zu erkennen und darauf zu reagieren. Ein effektives SIEM-System analysiert Daten in Echtzeit und nutzt Algorithmen zur Erkennung verdächtiger Muster. Wer sich in der Weiterbildung im Bereich Cybersecurity weiterbilden möchte, findet auf https://csvisor.de/ interessante Schulungsangebote. Dabei spielt die Kenntnis von Standards wie ISO 27001 eine zentrale Rolle für den beruflichen Erfolg in dieser Branche.

    ReplyDelete

Add your comment

All Right Reserved To Mukesh Jha.. Theme images by Jason Morrow. Powered by Blogger.