Java Exception Handling for Infinity - java

I am trying to write a program to equate the value of any number to any power, and I'm suppose to implement exception handling for exponents less than zero which i successfully did and also exception handle for when the value is too large to output i.e. infinity.
heres my power class which contains the function Power :
public class power
{
// instance variables - replace the example below with your own
public static double Power(double base, int exp) throws IllegalArgumentException
{
if(exp < 0){
throw new IllegalArgumentException("Exponent cannot be less than zero");
}
else if(exp == 0){
return 1;
}
else{
return base * Power(base, exp-1);
}
}
}
Heres the Test class :
public class powerTest
{
public static void main(String [] args)
{
double [] base = {2.0, 3.0, 2.0, 2.0, 4.0 };
int [] exponent = {10, 9, -8, 6400, 53};
for (int i = 0; i < 5; i++) {
try {
double result = power.Power(base[i], exponent[i]);
System.out.println("result " + result);
}
catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
}
}
heres the output of the test :
result 1024.0
result 19683.0
Exponent cannot be less than zero
result Infinity
result 8.112963841460668E31
my question is how can i get "result infinity" to say something else through ArithmeticException handling something along the lines of "Floating point Overflow"?
thanks in advance.

When you catch the exception, here
catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
just do
System.out.println("Floating point Overflow")
as well(if you want to add more) or replace the first print with this statement
This way like you said, "you get result infinity" to say something else through ArithmeticException handling"

Not sure if this is what you are looking for, but you can test for infinity/overflow with an if statement as well:
if( mfloat == Float.POSITIVE_INFINITY ){
// handle infinite case, throw exception, etc.
}
So in your situation, you would do something like this:
public static double
Power(double base, int exp) throws IllegalArgumentException
{
if(exp < 0){
throw new IllegalArgumentException("Exponent less than zero");
}
else if(exp == 0){
return 1;
}
else{
double returnValue = base * Power(base, exp-1);
if(returnValue == Double.POSITIVE_INFINITY)
throw new ArithmeticException("Double overflowed");
return returnValue;
}
}

Related

Java method references that take different numbers of characters?

I'm trying to apply retry logic to a number of methods. For example, I have method1(String) and method2(int, String) that I would like to retry up to a certain number of times.
I would ideally like:
int count = 0;
while (count < MAX_TRIES) {
try {
//run method
} catch (Exception e) {
//increment count
//throw e if count == MAX_TRIES
}
}
inside a method where I could pass in as a parameter method1 or method2. Is there any way to do this? Thanks!
Sure:
public <T> T retry(Callable<T> callable) throws Exception {
int count = 0;
while (true) {
try {
return callable.call();
} catch (Exception e) {
count++;
if (count == MAX_TRIES) {
throw(e);
}
}
}
}
And then
retry(() -> doSomething(a, b));
retry(() -> doSomethingElse(a));
This simple implementation is not very flexible, and could use better exception handling, though. You could use a library to do that (disclaimer: I'm the original author of this library), or at least see how it works and reuse some of its ideas.

Java: how to use try/catch block with return

The following code throws an exception if the list is empty and I want to getLast(). Also, I want to modify it with throw/catch-blocks, so that the message of the exception is going to appear on the console.
double foo(double[] numbers, double n) {
LinkedList<Double> list = new LinkedList<Double>();
for (double x : numbers) {
if (x > 0 && x <= n && x % 2 != 0) {
list.add(x);
}
}
Collections.sort(list);
return list.getLast();
}
My idea was:
double foo(double[] numbers, double n) {
LinkedList<Double> list = new LinkedList<Double>();
for (double x : numbers) {
if (x > 0 && x <= n && x % 2 != 0) {
list.add(x);
}
}
Collections.sort(list);
try{
return list.getLast();
} catch (Exception e){
System.out.println("caught: " + e);
}
return list.getLast();
}
Is this right? Did the exception get caught? What about the code after the throw/catch-block? Is it going to execute? If yes, is the exception going to be thrown again by return list.getLast();?
If list.getLast() throws an exception, it will be caught and the message will be printed. Then you will do the exact same thing and throw the exact same exception.
If you are relying on that exception being thrown when the list is empty, consider rethrowing the exception:
try {
return list.getLast();
} catch (Exception e) {
System.err.println("Caught: " + e);
throw e; // re-throw
}
// no "return" outside since we'll have thrown our previously caught error.
Is this right? If you want the exception to be thrown after print, it might be right functionality-wise, but calling getLast() twice is not the "right" way to do it.
Did the exception got caught? Yes, it did.
What about the code after the throw/catch-block? Is going to execute? Yes, it is going to execute. Since the exception was caught and not re-thrown, the execution continues as usual.
If yes, by return list.getLast(); is the exception going to be thrown again? Yes, the exception will be thrown again.
I think what you are looking for is:
try {
return list.getLast();
} catch (Exception e){
System.out.println("caught: " + e); // consider e.printStackTrace()
throw new RuntimeException("Failed to get last", e);
}
}
Why use try / catch at all. If all you want to do is determine if the list is empty what about checking list.size() != 0? Then return list.getLast() if true or Double.Nan and a message to the console if false.

How to execute Arithmetic Exception catch block in Java?

This is the code snippet:
public void actionPerformed(ActionEvent e){
int i1,i2;
try{
if(e.getSource()==b1){
.
.
.
else if(e.getSource()==b4){
double i1,i2;
i1=Integer.parseInt(t1.getText());
i2=Integer.parseInt(t2.getText());
i1=i1/i2;
l7.setText(i1+"");
}
else if(e.getSource()==b5){
i1=Integer.parseInt(t1.getText());
i2=Integer.parseInt(t2.getText());
i1=i1%i2;
l7.setText(i1+"");
}
}
catch(ArithmeticException ex2){
l7.setText("Debugging?");
JOptionPane.showMessageDialog(null,"Divide by zero exception!!");
//*WHY THIS SECTION IS NEVER BEING EXECUTED AFTER PERFORMING A DIVIDE BY ZERO i.e. ARITHMETIC EXCEPTION!*
}
catch(Exception ex){
JOptionPane.showMessageDialog(null,"Enter Values First!!");
}
}
The JRE is never executing the Arithmetic Exception catch statement, why?
Yes, it is handing it but it not producing the output that I expect it to produce!
It is automatically displaying, "Infinity" & "NaN" on my Java application!
Thanks!
Yes! Double and float have their own inbuilt values for infinity. There might be some other issues in your code that I'm not aware about.
Check these edits:
else if(e.getSource()==b4){
double i1,i2;
i1= Integer.parseInt(t1.getText());
i2= Integer.parseInt(t2.getText());
if(i1!=0 && i2 == 0){
throw new ArithmeticException();
}
else if(i2 == 0 && i1 == 0) {
throw new ArithmeticException();
}
i1= i1/i2;
l7.setText(i1+"");
}
This throw new ArithmeticException(); will force your code to execute the section that you are willing to execute!
Also, check this link: https://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html
Hope this helps!
Check these lines of code:
} else if (e.getSource() == b4) {
double i1, i2; // Comment this line to make it work like you need
i1 = Integer.parseInt(t1.getText());
i2 = Integer.parseInt(t2.getText());
i1 = i1 / i2;
l7.setText(i1 + "");
}
You have redeclared i1 and i2 to be double. The Double type defines inbuilt values for Infinity and NaN. That's the reason your code is not executing your ArithmeticException catch block.
Simply comment the double i1, i2; line to make it work like you need.
Update
If you want to show an error message, simply put a check:
} else if (e.getSource() == b4) {
double i1, i2;
i1 = Integer.parseInt(t1.getText());
i2 = Integer.parseInt(t2.getText());
if(i2==0){
throw new ArithmeticException("Cannot divide by zero");
}
i1 = i1 / i2;
l7.setText(i1 + "");
}
Hope this helps!

java catching stack overflow, getting msg display and return issues

So I'm using this recursive method to calculate the product of two numbers by recursive addition. I know that big numbers overflow the stack and my intention is to catch the stack overflow exception so the program don't crash. However, I don't understand why the output message displays several times in the same line and the return 0 is never passed out of the method. returning 0 is not that important, I'm forced to have a return statement. But instead of getting back 0, I'm getting back what seems random large numbers.
I would love for it to just display the message once and pass my value back or better yet terminate the method and just return the message. Any ideas?
here is the method:
public static long multiplicationRecursive(long num1, long num2) {
try {
if (num2 == 0) {
return 0;
} else {
return num1 + multiplicationRecursive(num1, num2 - 1);
}
} catch (StackOverflowError e) {
System.out.println("Recursion failed");
return 0;
}
}
You have to catch the error only once, at the point where you call the method for the first time (and remove the try/catch from the recursive method):
long result = 0L;
try {
result = multiplicationRecursive(num1, num2);
} catch (StackOverflowError e) {
System.out.println("Recursion failed");
result = 0L;
}
The problem with your approach is that sure, the exception gets caught, but then the method exits normally and goes back to the point where it was called recursively, effectively returning a bogus value.
whats happening is, when your recursive method call gets exception , it goes to catch block and since it has return 0, it comes back to caller with the value 0. and your caller is always will be as below
return num1 + multiplicationRecursive(num1, num2 - 1);
so num1+0 will happen internally and it returns the computed value till the exception.
since exception occured your recursive method will stop so it will print computed value as num1+0
see below code to have proper recursive handling
if (num2 == 0) {
return 0;
} else {
try{
//System.out.println("before oper");
if(multiplicationRecursive(num1, num2 - 1)==0){
return 0;
}
else{
return num1 + multiplicationRecursive(num1, num2 - 1);
}
}
catch (StackOverflowError e) {
System.out.println("Recursion failed");
return 0l;
}
//return 0;
}

Recursively splitting off perfect squares for display

I am attempting to create a recursive method that accepts an integer parameter and prints the first n squares
separated by commas, with the odd squares in descending order followed by the even squares in ascending order.
For example, if the input is 8, it should print the following output:
49, 25, 9, 1, 4, 16, 36, 64
My code so far is:
s and n have the same values initially, the only difference is that s changes as the code forwards while n doesn't change.
private static void genSquare(int s, int n) {
if (s >= 0 && s <= n) {
if (isOdd(s)) {
System.out.print(Math.pow(n, 2) + " ");
genSquare(s - 2, n);
}
if (s == 0 || s == 1) {
genSquare(1, n);
}
if (isEven(s)) {
System.out.print(Math.pow(n, 2) + " ");
genSquare(s + 2, n);
}
}
}
I have created a while loop version of it, which works perfectly. I just don't have the recursive version working.
Sample inputs would be using the same number for s and n.
Here is the code for the loop version:
private void genLoop(int s, int n) {
if (isEven(s)) {
s--;
}
while (s <= n) {
if (s == 1) {
System.out.print(1 + " ");
s++;
} else if (isOdd(s)) {
System.out.print(s * s + " ");
s -= 2;
} else if (isEven(s)) {
System.out.print(s * s + " ");
s += 2;
}
}
}
The problem is in this statement:
if(s == 0 || s== 1)
genSquare(1,n);
This causes the method to recurse infinitely. In fact, when you get to the point where s is zero or one, you have to make sure that you DON'T call genSquare recursively.
That's enough of a hint for you to figure the rest out for yourself ... and fix any other bugs.
In addition, there's a simpler way of squaring an integer ...
void calculateSquare(int n)
{
// odds descending and even ascending
int t=n;
if(n<=0)
return;
if(n%2==1)
{
// Calculate square now and print it also
System.out.println(n*n);
calculateSquare(--n);
}
else
{
calculateSquare(--n);
System.out.println(t*t);
}
}
This would do the job.
Try the following approach:
Assume your example where n is equal to 8. The square of 8 should printed last so you probably first should do a recursive call, then print the square of the current number.
Thinking about the task for n=7 the order of things given above should be reverted for odd numbers.
Yes it is good example for recursion . Try this it helps u
public class RecursionEx {
static int no = 0;
public static void main(String[] args) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Number");
try
{
no = Integer.parseInt(bufferedReader.readLine());
getSquares(no,0);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void getSquares(int number,int count)
{
if(number==1)
{
System.out.print(number);
count=1;
getSquares(number+1, count);
}
else
{
if(number%2!=0&&count==0)
{
System.out.print(number*number+",");
getSquares(number-2,0);
return;
}
if(count==0)
getSquares(number-1,0);
if(number%2==0&&count==1)
{
if(number<=no)
System.out.print(","+number*number);
if(number>=no)
return;
getSquares(number+2, count);
}
}
}
}

Categories