(while) insted of (try and catch)
Hi, could someone help please.
I need to know how to use while statement instead of try and catch to execute this program please help .
Code :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package testtrycatch;
/**
*
* @author group4
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int i =1;
int j =0;
try { System.out.println("Try block entered " +"i = " + i +" j = " +j);
System.out.println(i/j);
System.out.println("Ending try block");
}
catch (ArithmeticException e)
{ System.out.println("Arithmetic exception caught ");
}
System.out.println("After try block ");
return;
}
}
Re: (while) insted of (try and catch)
Re: (while) insted of (try and catch)
Quote:
Originally Posted by
Bryan
Although he could easily google a while loop, the problem is with this piece of code. If he doesn't understand what is happening then googling a while loop wont help that much.
b109 -
I don't understand why you are looking for a while loop? The try/catch is catching the exception generated here: System.out.println(i/j);
Without this piece of code, the exception is never generated.
The program is executed from the main method. What are you trying to achieve with a while loop? More information is needed.
An example of a while loop is this:
Code :
public class WhileLoopExample {
public static void main(String[] args) {
boolean myBoolean = true;
while(myBoolean){
System.out.println("JavaProgrammingForums.com");
}
}
}
This code will keep printing JavaProgrammingForums.com to the console until the myBoolean value is changed to false.
Re: (while) insted of (try and catch)
why dun wanna use try catch
Re: (while) insted of (try and catch)
well, there is the whole issue of looping. try/catch blocks execute the code inside them only once/call. Also, try/catch blocks are fairly slow (depending on the situation, can take milli-seconds where simple value checking using if/else or other conditionals are maybe an order or two of magnitude faster). If you want a pseudo replacement for try/catch, use if/else statements for the comparisons and handle the code flow as needed.
The only time you really should be using try/catch blocks is when there is a situation that you don't want a method to handle a certain type of situations, usually from bad data passed in.
Re: (while) insted of (try and catch)
Good answer helloworld :)
// Json
Re: (while) insted of (try and catch)
i see. thankyou for your enlightenment :D