Suppose I have a class, the requirement is that "change the following code to throw checked exception if "den" is 0, and change the function to catch that exception".
public class divide {
void divide(int num, int den){
System.out.println(""+(num/den));
}
void fun(){
divide(4,2);
}
}
Which of the following one is the correct way to throw exception?
Option 1:
void divide(int num, int den) throws Exception{
if(den==0){
throw new Exception("Dividebyzero");
}
System.out.println(""+(num/den));
}
void fun(){
try {
divide(4,2);
} catch (Exception e) {
}
}
Option 2: // I think this one is correct
void divide(int num, int den){
if(den==0){
throw new RuntimeException("Dividebyzero");
}
System.out.println(""+(num/den));
}
void fun(){
try {
divide(4,2);
} catch (RuntimeException e) {
}
}
Option 3:
void divide(int num, int den) throws Exception{
if(den==0){
throw new RuntimeException;
}
System.out.println(""+(num/den));
}
void fun(){
try {
divide(4,2);
} catch (Exception, RuntimeException) {
}
}
This problem came from one of the Java exercises. I have learned Java for several years but I am kind of confused about the try catch throw. Personally, I think that option 2 is correct because we only throw the exception once, or I am wrong?