设计一个异常类FlowException,该类继承自Exception,getMsg()方法返回错误信息。 (格式:id的值:msg的值) 2. 定义一个异常测试类ExceptionTest – 定义一个方法test,该方法接收2个整型的参数num1和num2,如果num1 - num2 <= 0,则抛出异常FlowException,错误信息为“404:Under Value Err”;如果num1 - num2 >= 1000,则抛出异常FlowException,错误信息为”405:Over Value Err” – 在main方法中通过键盘输入2个数,测试方法test并显示错误信息。 FlowException +int id +FlowException(int id, String msg) +String getMsg(
时间: 2024-02-09 21:10:00 浏览: 64
实现一个自定义异常类IntegerException
)```
public class FlowException extends Exception {
private int id;
private String msg;
public FlowException(int id, String msg) {
this.id = id;
this.msg = msg;
}
public String getMsg() {
return id + ":" + msg;
}
}
```
```
import java.util.Scanner;
public class ExceptionTest {
public static void test(int num1, int num2) throws FlowException {
if (num1 - num2 <= 0) {
throw new FlowException(404, "Under Value Err");
}
if (num1 - num2 >= 1000) {
throw new FlowException(405, "Over Value Err");
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please input num1: ");
int num1 = scanner.nextInt();
System.out.print("Please input num2: ");
int num2 = scanner.nextInt();
try {
test(num1, num2);
} catch (FlowException e) {
System.out.println("Exception: " + e.getMsg());
}
}
}
```
阅读全文