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-18 21:40:37 浏览: 20
Here is the implementation of the classes MyException and MyExceptionTest as described in the question:
```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, n2 = 10000;
try {
System.out.println(multiply(n1, n2));
} catch (MyException e) {
System.out.println(e.getMessage());
}
}
}
```
In the main method, we call the multiply method with two large integers and handle the MyException that may be thrown by the method. If the product of the two integers is within the range [-32768, 32767], it is printed to the console. Otherwise, the error message is printed.