Define an exception class MyException, which is thrown if the result is not in the range [-32768, 32767] in the method multiply that computes the product of two integers. Define a main class MyExceptionTest that contains the following methods: public static int multiply(int n1, int n2) throws MyException { int result; result=n1*n2; if (result<-32768 || result>32767) throw new MyException(n1+"*"+n2+"的积超出[-32768,32767]的范围!"); return result; } Finally, write codes that can print the product of two integers in the main method of the main class.
时间: 2024-03-22 13:37:37 浏览: 20
Here is the implementation of the MyException class and MyExceptionTest class:
```java
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
public class MyExceptionTest {
public static int multiply(int n1, int n2) throws MyException {
int result;
result = n1 * n2;
if (result < -32768 || result > 32767)
throw new MyException(n1 + "*" + n2 + "的积超出[-32768,32767]的范围!");
return result;
}
public static void main(String[] args) {
int n1 = 10000;
int n2 = 20000;
try {
int result = multiply(n1, n2);
System.out.println(n1 + " * " + n2 + " = " + result);
} catch (MyException e) {
System.out.println(e.getMessage());
}
}
}
```
In the main method of the MyExceptionTest class, we define two integers n1 and n2, then we call the multiply method with these two integers as parameters. If the result is not in the range [-32768, 32767], a MyException is thrown. We catch the exception and print out the error message. If the result is within the range, we print out the product of the two integers.