457,013 views
25 votes
25 votes
Create a public class called Exceptioner that provides one static method exceptionable. exceptionable accepts a single int as a parameter. You should assert that the int is between 0 and 3, inclusive.

If the int is 0, you should return an IllegalStateException. If it's 1, you should return a NullPointerException. If it's 2, you should return a ArithmeticException. And if it's 3, you should return a IllegalArgumentException.

User Hhanesand
by
3.5k points

1 Answer

16 votes
16 votes

Answer:

// Begin class declaration

public class Exceptioner {

// Define the exceptionable method

public static void exceptionable(int number){

//check if number is 0.

if(number == 0) {

//if it is 0, return an IllegalStateException

throw new IllegalStateException("number is 0");

}

//check if number is 1

else if(number == 1) {

//if it is 1, return a NullPointerException

throw new NullPointerException("number is 1");

}

//check if number is 2

else if(number == 2) {

//if it is 2, return an ArithmeticException

throw new ArithmeticException("number is 2");

}

//check if number is 3

else if(number == 3) {

//if it is 3, return an IllegalArgumentException

throw new IllegalArgumentException("number is 3");

}

}

}

Sample Output:

Exception in thread "main" java.lang.ArithmeticException: number is 2

at Main.exceptionable(Main.java:26)

at Main.main(Main.java:36)

Step-by-step explanation:

The code is written in Java with comments explaining important parts of the code.

A sample output for the call of the method with number 2 is also provided. i.e

exception(2)

gives the output provided above.

User Gioravered
by
3.1k points