2. 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-24 21:36:53 浏览: 46
Here is the implementation of the MyException class and the 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 = 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 {
int result = multiply(n1, n2);
System.out.println(n1 + " * " + n2 + " = " + result);
} catch (MyException e) {
System.out.println(e.getMessage());
}
}
}
```
In the main method, we call the multiply method to compute the product of two integers. If the result is out of the range [-32768, 32767], a MyException will be thrown. We catch the exception and print the error message.
阅读全文