how to solve Arithmetic Exception in java - exception

Below is my code :
public class prg34 {
public static void main(String[] args) {
int a=6;
for(int i=0;i<10;i++){
System.out.println(a/i);
}
}
}
Exception:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at run.prg34.main(prg34.java:8)
How to solve above Arithmetic Exception in java ?

You are trying to divide by zero in your first iteration. Change your first condition of i = 0, to something other than zero.
You cannot divide by 0, as I believe Java handles the division by zero error by a processor exception which triggers an interrupt.
Your first iteration is trying 6/0.
public static void main(String[] args) {
int a=6;
for(int i=1;i<10;i++){
System.out.println(a/i);
}
}

The first loop in your code gives an exception because you are trying to divide 6 by 0 i.e the ArithmeticException.
In order to fix this you must have to use try catch block. I've illustrated full code here. Please fix this.
public class prg34 {
public static void main(String[] args) {
int a=6;
try {
for(int i = 0; i < 10; i++) {
System.out.println(a/i);
}
}catch(ArithmeticException e) {
System.out.println("Division by zero is not possible. "+ e);
}
}
}

Related

how can use exception handling when we are calling a function in java

This is my code i want to call a method with another parameter with use of exception handling i want to sorround with try and catch my calling function. That Have a error of internal local variable is not assigned so i want to sorround it by try catch
how can i sorround a method calling with parameter
public void nik() {
System.out.println("nik or me ghar ja rhe he");
}
public int nik(int time) throws MyMagicExcep {
int a throw ;
System.out.println("nik or me "+a+time+" bje ghar jayege");
return 0;
}
public static void main(String[] args) {
first obj = new first();
// System.out.println();
obj.nik();
try{
System.out.println("harsh bhaiya mja nhi aaya");
obj.nik(1);}
catch(MyMagicExcep e) {
System.out.println("harsh bhaiya mja nhi aaya");
}
obj.nik();
}
}```

Java Try Catch Decorator

I have a class with many functions
public class Test {
public void a() {
try {
doSomething1();
} catch (AException e) {
throw new BException(e.getMessage(), e.getCause());
}
}
public void b() {
try {
doSomething2();
} catch (AException e) {
throw new BException(e.getMessage(), e.getCause());
}
}
}
In each method, an exception of certain type is caught and converted to another exception and thrown.
I want to remove duplication.
You may remove duplication using lambda:
The CallableEx takes any exception, in case you are working with checked exception. You would not need it if AException was an unchecked exception. Callable interface won't help you much because it throws an Exception and not your AException: you would have to check for instance and so on.
You could probably write the body instead of this::doSomething1, but I advise against it: this makes the code clearer and it separates concerns.
You could probably also use an annotation processor to do the same job and to rewrite the method in order to wrap your AException into a BException. You would not have duplication in your Java code, but your bytecode certainly will.
Here the example with lambda:
public class Test {
#FunctionalInterface
interface CallableEx<T, E extends Exception> {
T run() throws E;
}
private <T> void handleException(CallableEx<T, AException> forrestGump) {
try {
return forrestGump.run();
} catch (AException e) {
throw new BException(e.getMessage(), e.getCause());
}
}
public String a() {
return handleException(this::doSomething1);
}
public int b(int a, int b) {
return handleException(() -> this.doSomething2(a, b));
}
public <T extends Foobar> void c(T my) {
handleException(() -> this.doSomething3(my));
}
private String doSomething1() {return "A";}
private int doSomething2(int a, int b) {return a + b;}
private <T extends Foobar> void doSomething3(T my) {my.foo();}
}

Why am I getting an java.lang.ArrayIndexOutOfBoundsException exception?

I am writing the following code for a program that returns a boolean of whether or not three consecutive numbers in an array of ints add up to 7. I am getting the following exception instead of the output that I want: "java.lang.ArrayIndexOutOfBoundsException:5". Please can someone explain how I can fix this issue?
public static void main(String[] args) {
int[] numbers ={2,1,5,1,0};
System.out.println(luckysevens(numbers));
}
public static boolean luckysevens(int array[]) {
boolean isLucky= false;
for (int i=0; i<=array.length; i++){
if (array[i]+array[i+1]+array[i+2]==7){
isLucky=true;
}
else {
i++;
}
}
return isLucky;
}
}
Because you are accessing the array elements beyond its length.
For an array of length L, you can access elements in index range of 0 to L-1.
The above exception arises when you access elements beyond this index range.
You don't even need to increment in the else condition.
public static void main(String[] args) {
int[] numbers ={2,1,5,1,0};
System.out.println(luckysevens(numbers));
}
public static boolean luckysevens(int array[]) {
boolean isLucky= false;
for (int i=0; i<array.length-2; i++){
if (array[i]+array[i+1]+array[i+2]==7){
isLucky=true;
}
}
return isLucky;
}
}
You're comparing from 0 - 5 (i.e. 6 elements, but your array has only 5), so you're going out of the bounds.
All you have to do is to go from 0 - array.length-1; therefore have to change condition part i<=array.length; to like this i<(array.length-1);
public static void main(String[] args) {
int[] numbers ={2,1,5,1,0};
System.out.println(luckysevens(numbers));
}
public static boolean luckysevens(int array[]) {
boolean isLucky= false;
for (int i=0; i<(array.length-1); i++){
if (array[i]+array[i+1]+array[i+2]==7){
isLucky=true;
}
else {
i++;
}
}
return isLucky;
}
public static void main(String[] args)
{
int[] numbers ={2,1,5,1,0};
System.out.println(luckysevens(numbers));
}
public static boolean luckysevens(int array[])
{
boolean isLucky= false;
//Use array.length-2 in the code
for (int i=0; i<=array.length-2; i++)
{
if (array[i]+array[i+1]+array[i+2]==7)
{
isLucky=true;
return isLucky;
}
}
return isLucky;
}

Exceptions handling trouble

Trying to add divide by zero exception in my calculator project through the try/catch block:
private class Calculate implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
if (operation.equals("/")) {
display.setText(Double.toString(getResult() / Double.parseDouble(display.getText())));
setResult(Double.parseDouble(display.getText()));
}
else if (operation.equals("*")) {
display.setText(Double.toString(getResult() * Double.parseDouble(display.getText())));
setResult(Double.parseDouble(display.getText()));
}
else if (operation.equals("-")) {
display.setText(Double.toString(getResult() - Double.parseDouble(display.getText())));
setResult(Double.parseDouble(display.getText()));
}
else if (operation.equals("+")) {
display.setText(Double.toString(getResult() + Double.parseDouble(display.getText())));
setResult(Double.parseDouble(display.getText()));
}
if (display.getText().endsWith(".0")) {
display.setText(display.getText().replace(".0", ""));
}
calculationMade = true;
operation = "";
}
catch (IllegalArgumentException exc) {
display.setText("You cannot divide by zero!");
}
}
}
But in this way it still writes me "Infinity" in a text field. Can anybody suggest where i'm wrong please?
When working with double, zero division returns Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY (depending on operand signs)
System.out.println(1.0d/0d);
System.out.println(-1.0d/0d);
System.out.println(1.0d/-0d);
System.out.println(-1.0d/-0d);
Only non-decimal arithmetic throws an exception on zero division. And the exception is not an IllegalArgumentException but an ArithmeticException.

How do I implement a fibonacci sequence in java using try/catch logic?

I know how to do it using simple recursion, but in order to complete this particular assignment I need to be able to accumulate on the stack and throw an exception that holds the answer in it.
So far I have:
public static int fibo(int index) {
int sum = 0;
try {
fibo_aux(index, 1, 1);
}
catch (IntegerException me) {
sum = me.getIntValue();
}
return sum;
}
fibo_aux is supposed to throw an IntegerException (which holds the value of the answer that is retireved via getIntValue) and accumulates the answer on the stack, but so far I can't figure it out. Can anyone help?
I don't know what your implementations for fibo_aux and IntegerException look like, but the following two implementations work with your existing code (I don't think there's anything wrong with the code you posted, so I assume something is awry in either fibo_aux or IntegerException). Maybe you'll find this helpful.
public static void fibo_aux(int index, int a, int b) throws IntegerException
{
if (--index > 0)
fibo_aux(index, b, a + b);
else
throw new IntegerException(a + b);
}
An implementation for IntegerException:
public class IntegerException extends Exception
{
private static final long serialVersionUID = -6795044518321782305L;
private Integer intValue;
public IntegerException(int i)
{
this.intValue = i;
}
public Integer getIntValue()
{
return intValue;
}
}
Here you go :
public class ExcFib {
/**
* #param args
*/
public static void main(String[] args) {
new ExcFib().fibo ( 10 );
}
class FiboException extends Throwable
{
public int n;
public FiboException(int n)
{
this.n = n;
}
private static final long serialVersionUID = 1L;
}
public void fibo(int idx) {
try {
fibo_aux(idx-1,1,1);
} catch (FiboException e) {
System.out.println ( "F(" + idx + ") = " + e.n );
}
}
private void fibo_aux(int i, int j, int k) throws FiboException {
if ( i < 1 )
{
throw new FiboException(k);
}
fibo_aux(i - 1, k, j + k );
}
}