user6119494
user6119494

Reputation: 65

Throw exception in Java

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?

Upvotes: 3

Views: 6867

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533820

Which of the following one is the correct way to throw exception?

I wouldn't complicate the code, instead I would use the exception it already throws.

void printDivide(int num, int den) throws ArithmeticException {
    System.out.println(num / den);
}

Using a different exception is not just more complicated, it's confusing.


Lets set it is a different example, then IllagelArgumentException is a good choice for an illegal argument, like creating an array

void createArray(int size) {
    if (size < 0)
        throw IllegalArgumentException("Size must be non-negative " + size);
    this.array = new int[size];
}

Upvotes: 4

Related Questions