Prevent program from getting terminated after exception handling [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Is there anyway to handle the exceptions in Java and prevent the program from getting terminated? For instance when the user enters an invalid number into a calculator, zero in this example for division in the denominator, I don't want the program to get terminated and show the handled exception message. I want the program to continue and ask for another input.
Could anyone clarify it with a practical example for me?

Simple: put a loop around the whole try catch block; like:
boolean loop = true;
while (loop) {
try {
fetch input
loop = false;
} catch (SomeException se) {
print some message
}
does the job in general.

Try this:
boolean exceptionOccured;
do {
try {
exceptionOccured = false;
// code to read input and perform mathematical calculation
// eg: a = 10/0;
} catch(Exception e) {
exceptionOccured = true;
System.out.pritnln("Invalid input! Please try again");
} finally {
// some code that has to be executed for sure
}
} while(exceptionOccured);
First the code inside the try block will be executed. When an execption occurs (like division by zero), execution of code jumps from try block to catch block where you can write your logic to loop the try-catch block.

Related

How to handle Number format Exception? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
My requirement is to check divisibility of the input by 7, for the various test cases and I have written this code but it is throwing me NumberFormat Exception
class Solution{
int isdivisible7(String num){
// code her
long i= Long.parseLong(num);
// to convert string into long
if(i%7==0)
return 1;
else
return 0;
}
}
How can I handle the exception and return the result for any (both valid and invalid) input ?
If the input num is not number, then it will throw NumberFormatException, so you just have to catch it. Also, function names should be in camel case. And finally, it's better to make the function return boolean rather then int of values 0 and 1.
boolean isDivisibleBy7(String num){
try {
long i = Long.parseLong(num);
return i % 7 == 0;
} catch (NumberFormatException e) {
// print some error message if you want
System.out.println("You haven't passed number");
return false;
}
}

Problems to validate a number in try-catch block in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am trying to create a method to introduce an int with NetBeans, but I have a problem when I run the method, the order of console messages is not correct, someone knows what the problem is:
public static void main(String[] args)
{
Scanner teclado = new Scanner(System. in );
int num;
boolean error;
public int introducirDatos()
{
do
{
error = false;
try
{
System.out.println("Introduzca un número entero: ");
num = Integer.valueOf(teclado.nextLine());
}
catch (NumberFormatException e)
{
System.err.println("Debe introducir un número y sin decimales, vuelve a intentarlo.\n");
error = true;
}
} while (error == true);
return num;
}
}
Thanks.
I believe you are running the code in an IDE - IntelliJ IDEA or Eclipse. The line System.out.println("Introduzca un número entero: "); prints to standard OUT, but System.err.println("Debe introdu... prints to standard ERROR. That's why the output gets messed up. Replace System.err with System.out for the messages being printed nicely one after another.
BTW you haven't specified which language you are using. Is it Java? You might want to update the question tags.

change value of an integer using parseInt [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
So I'm writing a method that is supposed to prompt the user to enter their pin number as a string, which is then converted to an int (or not depending on if it throws an exception), which I need to be assigned to the int pinNumber.
The problem I'm having is that the new object is assigned a pin number by the constructor when created, and this value isn't being changed when the below method is executed. What am I missing?
public boolean canConvertToInteger()
{
boolean result = false;
String pinAttempt;
{
pinAttempt = OUDialog.request("Enter your pin number");
try
{
int pinNumber = Integer.parseInt(pinAttempt);
return true;
}
catch (NumberFormatException anException)
{
return false;
}
}
EDIT: Changed pinAttempt to pinNumber (typo)
Have a look at this block
try
{
int pinNumber = Integer.parseInt(pinAttempt);
return true;
}
pinNumber will only have the value you expect in the scope of the try block.
I think you want to do
try
{
this.pinNumber = Integer.parseInt(pinAttempt);
return true;
}
instead.

java break loop not working [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a break label in my java code but it doesn't jump to the label when I go to the break statement in my code:
OUTERMOST:for(String s :soso){
if(wasBreaked){
//code never enters this loop
Log.e("","WASBREAK = FALSE");
wasBreaked = false;
}
if(true){
Log.e("","WASBREAK = TRUE GOING TO OUTERMOST");
wasBreaked = true;
break OUTERMOST;
}
}
Break statement is not really a goto statement as in other programming languages like C.
What your code does instead is, break from the loop which has label OUTERMOST. I would have thought you need continue OUTERMOST; instead of break. But to me it really doesn't makes sense as you dont have further any statement post continue (now break in your code) and it's going to continue anyways irrespective of whether you say explicitly continue or not.
public class Test {
public static void main(String[] args) {
String soso[]={"1","2"};
boolean wasBreaked=false;
OUTERMOST:for(String s :soso){
if(wasBreaked){
Log.e("","WASBREAK = FALSE");
wasBreaked = false;
}
if(true){
Log.e("","WASBREAK = TRUE GOING TO OUTERMOST");
wasBreaked = true;
System.out.println("before break");
break OUTERMOST;//use continue in place of break here for going to label
}
System.out.println("Inside outermost loop");
}
System.out.println("outside outermost loop");
}
}
I tried this and it works
it gives output
before break
outside outermost loop
For going back to label you should use continue keyword rather than break in code. After using continue the output will be like
before break
before break
outside outermost loop

Try-Catch Exception handling [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
try {
System.out.println("how many times");
rollnumber = scanner.nextInt();
nigh=2;
}catch (Exception e){
System.out.print("invalid. re-enter");
}
}while (nigh==1);
It keeps printing out infinity "invalid re-enterhow many times"
You get into an infinite loop because scanner.nextInt(); does not consume characters from the input on error. Change the catch clause as follows to make it work:
try {
... // Your code
} catch (Exception e){
System.out.print("invalid. re-enter");
scanner.nextLine();
}

Categories