This is my first time using exception handling so be gentle. I have a simple blob class that accepts an ID, the id must be between 30 and 50 or else an exception is thrown.
public class Blob {
int id;
public Blob() {
}
public Blob(int id) throws Exception {
this.id = id;
if (id < 30 || id > 50)
throw new Exception ("id = " +id+ ", must be between 30 and 50 inclusive");
}
}
It should prompt the user to enter an id, and throw the exception if it's not between 30 and 50, and should continue until the user enters a valid input and then simply displays the id number.
public class BlobCreator {
public static void main(String[] args) {
int id;
Scanner scan = new Scanner(System.in);
System.out.println("Enter ID number: ");
id = scan.nextInt();
do {
try {
Blob b = new Blob(id);
}
catch (Exception e) {
System.out.println(e);
}
System.out.println("Enter a different ID: ");
id = scan.nextInt();
}
while(true);
}
System.out.println("Blob ID: " +id);
}
I think that I am using the throw and catch correctly, but my loop isn't working correctly so I think that should be a simple fix but I can't get it just right. Also is using a while loop like I have the best way for this situation or is there a better way to loop through throw and catch?
Thanks for any and all help
You should place the break; after the code is executed successfully.
do {
try {
Blob b = new Blob(id);
break;
}
catch (Exception e) {
System.out.println(e);
}
System.out.println("Enter a different ID: ");
id = scan.nextInt();
} while(true);
So each time the loop would reach the end of its body, it would break out of the loop. You only should break after the blob is created successfully. Although I dont see why you put a break anyway. The while loop can check if the entered input was valid and simply stop the loop.
I modified the while in a do-while loop... By using true the loop will run forever, unless no exception is thrown by the constructor... This makes the code more generic (if you modify the conditions of the blob-construction, you don't have to modify the condition of the while loop).
Sorry, its kind of late to the party. Hope users who endup here may find this useful.
The use of break keyword is discouraged
Here is a very simple implementation to break away after implementing a retry mechanism
This iterates over the loop for the specified number of times and also if the exception still persists, then the exception is thrown. This can be leveraged for an actual real world scenario where the resttemplate might actually result in IO/Network errors and can be retried in those cases
public class TestClass {
public static void main(String[] args) throws Exception {
try {
int c = anotherM();
System.out.println("Now the value is" + c);
} catch (Exception e) {
System.out.println("Inside" + e);
}
}
public static int anotherM() throws Exception {
int i = 4;
Exception ex = null;
while (i > 0) {
try {
System.out.println("print i" + i);
throw new IOException();
// return i;
} catch (Exception e) {
System.out.println(e);
i--;
if (i == 1) {
ex = new Exception("ttt");
}
}
}
if (ex != null) {
throw new Exception("all new");
} else {
return i;
}
}
}
Related
I wanted to make an input which accepts numbers from 1 - 10 and prints the range.
I need to check if the input is an integer (check), check if the range is 0-10 (check), and if it's not any of those things, to ask the user again. So, a recursive method?
Currently I have this:
import java.util.Scanner;
import java.util.InputMismatchException;
public class FinalTest {
public static void main (String [] args) {
Scanner in = new Scanner(System.in);
int k = 0;
System.out.print("int - ");
try {
k = in.nextInt();
} catch (InputMismatchException e) {
System.out.println("ERR: Input");
System.exit(1);
}
if(k <= 10 && k > 0) {
for(int j=1; j <= k; j++) {
System.out.println(j);
}
} else {
System.out.println("ERR: Oob");
System.exit(1);
}
}
}
I would like to replace the "System.exit()" so that it re attempts to ask the user for input again.
calling main(); produces an error.
How do I correctly call the main method in this case?
Two choices here:
actually create a method and call that
simply use a loop
Loop could go like:
boolean askForInput = true;
while ( askForInput ) {
try {
k = in.nextInt();
askForInput = false;
} catch ...
print "not a number try again"
}
But beyond that: you still want to put this code into its own method. Not because that code should call itself, but for clarity reasons. Like:
public static int askForNumber(Scanner in) {
... code from above
return k;
}
And to answer your question: you do not want to use recursion here. You want to loop; and yes, recursion is one way to implement looping, but that is simply overkill given the requirement you want to implement here.
And for the record: when creating that helper method, you can actually simplify it to:
public static int askForNumber() {
while ( askForInput ) {
try ...
return in.nextInt();
} catch ...
print "not a number try again"
}
}
Beyond that: you typically use recursion for computational tasks, such as computing a factorial, or fibonacci number, ... see here for example.
for the part of the recursive method printing a range:
public void printAscending(int n) {
if (n > 0) {
printAscending(n - 1);
System.out.println(n);
}
}
I think using recursion is just too much for something that simple and would probably be more expensive. You can add a while loop around your scanning bit until the entered value is valid. I would also put the printing loop out of the while to not have to test a condition before printing since if you get out of the while loop, it means number if valid. You could test just the -1 value to exit process.
public class FinalTest
{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int k = 0;
do
{
System.out.print("int - ");
try
{
k = in.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("ERR: Input");
System.exit(1);
}
}
while(!(k>0 && k<=10) && k!=-1);
if(k!=-1)
{
for(int j=1; j<=k; j++)
{
System.out.println(j);
}
}
else
{
System.out.println("Bye Bye.");
}
}
}
Okay, so what I personally do when I need to use recursion is I create a separate function/method for it. And when I need to restart the method, I just call it within itself. So it would be something like this:
private void recursiveMethod() {
// do stuff . . .
if (yourCondition) {
//continue to next piece of code
} else {
recursiveMethod();
}
}
But in big projects, try to stay away from recursion because if you mess up, it can
I created the below code for understanding purpose.
In below code there is an error in try block so it should go to catch block and print 15 also as finally block is always executed we should also get 20.
But in the output I am getting only 20 and not 15 in the output.
Kindly advise how why there is this descripancy.I am a begineer in Java.
Also make any necessary changes in the program if needed to get both 15 and 20 as output.
package javaapplication91;
public class NewClass
{
public static void main(String[] args)
{
NewClass n = new NewClass();
int z = n.m1();
System.out.println("z = " + z);
}
public int m1()
{
try
{
int a = 10/0;
System.out.println("Exception created");
return 10;
}
catch(ArithmeticException ae)
{
return 15;
}
finally
{
return 20;
}
}
}
You can return only one value from method if your method declaration return value type is int.
When you cath exception ArithmeticException you try to return 15, but you got 20, because finally block execute allways in the end of try catch block and it would be last return statement.
You can read about finally here (Java Tutorial)
If you want return both values, you can use array or list like this:
public List<Integer> m1() {
List<Integer> returnValues = new ArrayList<Integer>();
try {
int a = 10/0;
System.out.println("Exception created");
returnValues.add(10);
} catch(ArithmeticException ae) {
returnValues.add(15);
} finally {
returnValues.add(20);
return returnValues;
}
}
The return inside the ArithmeticException will be overridden by the finally return and that will be returned to your function.
Advice is , finally can be used only when closing a file or recovering resources.
I am new to Java. I am trying to create a Java Program that has the ability to retry itself when an exception occur in the program (which work fine). Now the problem I have now is in the for loop. In this code, when something went wrong in the for loop, the program itself will jump out of that loop and go to the catch method. After that if the retry is less than MAX_RETRIES, then the program will relaunch from the beginning. This is what I am struggling with. What I want is let say if there is an exception occur in the for loop when printing let say 5, I want the program to retry where the exception in the for loop occur not relaunch from the beginning. Are there ways to do it? I am struggling with this for a while and cannot seems to find a way to do it. Help and code for reference will be appreciated. This is the best way I can think of to simplify my code. In my real application, the for loop I have right now is to Iterate though a list of record from the database.
main.java
public class main {
private static int retryCounter = 1;
private static int MAX_RETRIES = 3;
public static void main(String[] args) {
int retry = 1;
try {
while (retry <= MAX_RETRIES) {
//method1
//stuff code
//more code
//method2
for (int i = 0; i < 11; i++) {
System.out.println("i");
}
}
System.out.println("-----Finish Process-----");
break;
} catch (Exception e) {
e.printlnStackTrace();
retry++;
if (retry == MAX_RETRIES) {
System.out.println("Program retried" + retry);
System.out.println("Program Terminated");
}
}
}
I think it solve your problem
public class main {
private static int retryCounter = 1;
private static int MAX_RETRIES = 3;
public static void main(String[] args) {
int retry = 1;
while (retry <= MAX_RETRIES) {
try {
//method1
//stuff code
//more code
//method2
int i=0;
while (i < 11) {
try {
System.out.println(i);
i++;
} catch (Exception e) {
e.printStackTrace();
i++;
if (i == MAX_RETRIES) {
System.out.println("Program retried" + retry);
System.out.println("Program Terminated");
}
}
}
retry++;
} catch (Exception e) {
e.printStackTrace();
retry++;
if (retry == MAX_RETRIES) {
System.out.println("Program retried" + retry);
System.out.println("Program Terminated");
}
}
}
System.out.println("-----Finish Process-----");
}
}
I have an idea that might help. I can't show any example code, but it might be possible to set up a flag/signal1 after you complete each step in executing the program. Then, when the program retries, it can automatically skip to that point in code where it last stopped.
1: I don't know what it's called in java
I hava a method called test() that throws an exception.
I want to write a loop that executes as long as it throws an exception, and breaks when it no longer throws an exception.
Can any one hint me on the logic that must be use?
For example I tried,
int i=0;
while(test())
{
i++;
}
System.out.println(i);
int i=0;
while (true) {
try {
test();
break;
} catch (Exception e) {
i++; // Loop will continue
}
}
I'm trying to implement a time limit a user has to answer a question in a quiz. Although I have found quite a bit on timmers I don't know how to piece it all together.
I want the user to have 15 seconds to answer the question. If they answer it in time, it checks if answer the answer is correct and then asks them if they want to continue to the next question.
If the user gives no response in the 15 seconds then it should say that the answer is incorrect and gives them the option to move to the next question.
Here is what I have so far.
for(int i=0; i<quiz.getQuizQuestions().size(); i++){
super.getQuestion(i);
//While timer is less than 15 seconds
getResponse(i, questionStart);
//If time has run out output "You have run out of time"
super.nextQuestion();
}
It is probably worth knowing:
super.getQuestion(i) is just printing the question being asked
getResponse() is waiting for keyboard input. if something is entered then it checks to see if the user is correct.
super.nextQuestion() asks the user is they want to move onto the next question
Thanks in advance
EDIT: It would also be amazing if it was easy to implement a counter that counted down from 15 when converting this into a GUI.
uses ExecutorService and Future to make sure we read a line or interrupt it. Code is a little longer than I expected... Let me know if something is unclear:
import java.util.concurrent.*;
import java.io.*;
public class Test {
public static void main(String[] args) throws java.io.IOException {
Question q = new Question();
System.out.println("You have 5 seconds: " + q.toString());
String userAnswer = null;
ExecutorService ex = Executors.newSingleThreadExecutor();
try {
Future<String> result = ex.submit(new GetInputLineCallable());
try {
userAnswer = result.get(5, TimeUnit.SECONDS);
if (Integer.valueOf(userAnswer) == q.getAnswer()){
System.out.println("good!");
}
else{
System.out.println("Incorrect!");
}
} catch (ExecutionException e) {
e.getCause().printStackTrace();
} catch (TimeoutException e){
System.out.println("too late!");
return;
} catch (InterruptedException e){
System.out.println("interrupted?");
e.getCause().printStackTrace();
}
} finally {
ex.shutdownNow();
}
}
}
class GetInputLineCallable implements Callable<String> {
public String call() throws IOException {
BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));
String input = "";
while ("".equals(input)) {
try {
while (!inp.ready()) {
Thread.sleep(100);
}
input = inp.readLine();
} catch (InterruptedException e) {
return null;
}
}
return input;
}
}
class Question{
int p1, p2;
public Question(){
p1 = 2;
p2 = 3;
}
public String toString(){
return String.format("%d + %d = ?", p1, p2);
}
public int getAnswer(){
return p1+p2;
}
}
long startTime = System.currentTimeMillis();
while(System.currentTimeMillis() - startTime < 15000){
if(userAnswered){
break; // if there is an answer we stop waiting
}
Thread.sleep(1000); // otherwise we wait 1 sec before checking again
}
if(userAnswered){
goToNextQuestion();
}
else {
handleTimeOut();
}