I am trying to catch the exception in the following code by using a try catch block or throws exception method .i have tried out using try catch block and throws exception method at different places in the code but i am stil not able to catch the exception
package thowsexception;
import java.io.IOException;
import java.rmi.AccessException;
public class IOexception {
public int example1(int i, int j) throws ArithmeticException {
int k ;
if (i == 0){
throw new ArithmeticException("cannot Divide By 0");
}
return i /j ;
// try {
//
// k = i/j ;
// }
//
// catch (ArithmeticException e){
//
// System.out.println("Error: Don't divide a number by zero");
// }
}
}
Main Class
package thowsexception;
import java.io.IOException;
public class IOexception {
public static void main(String[] args) throws ArithmeticException {
example e = new example();
e.example1(5,0);
}
}
You can fix this in tow different ways
public int example1(int i, int j) throws ArithmeticException {
if (j == 0) {// you should check j instead of i
throw new ArithmeticException("cannot Divide By 0");
}
return i / j;
}
OR
public int example1(int i, int j) throws ArithmeticException {
try {
return i / j;
}
catch (ArithmeticException e) {
throw new ArithmeticException("Error: Don't divide a number by zero");
}
}
But the first one is correct than the second one, because the unchecked exceptions represent programming error, and programming error should be fixed and Most of the times these exception occurs due to the bad data provided by user during the user-program interaction, so we should prevent these type of error instead of catch it.
Read more about better-understanding-on-checked-vs-unchecked-exceptions-how-to-handle-exception-better-way-in-java
Your current code states this:
if (i == 0) {
throw new ArithmeticException("cannot Divide By 0");
}
return i/j ;
The problem with this is that you are checking if the numerator of the fraction, i, is equal to 0. If a numerator is 0, the fraction is fine, because you aren't dividing by 0. You need to check if j == 0, because you are dividing by j.
if (j == 0) {
throw new ArithmeticException("cannot Divide By 0");
}
return i/j ;
is the correct code.
Here is what can you do to catch the exception
Main Class
package thowsexception;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
IOexception e = new IOexception();
try { e.example1(5,0);
}
catch (ArithmeticException e1){
}
}
}
IOexception Class
package thowsexception;
import java.io.IOException;
import java.rmi.AccessException;
public class IOexception {
public void example1(int i, int j) {
int k = i/j;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.