具体内容
1)假如要从命令行获得两个整数,自定义两个异常类来描述可能发生的异常:ParameterNumberException(参数个数异常),ParameterFormateException(参数格式异常),设计一个类,在check(String args[])方法中通告这两个异常,在main方法中判断相应的情况下触发异常,然后捕获异常,对它们进行处理。(知识点:异常处理机制)
判断长度和类型不准,相应条件分支抛出对应的自定义异常即可
具体代码:
Custom.java
import java.util.Scanner;
public class Custom {
public static boolean check(String args) {
for (int i = 0; i < args.length(); i++) {// 判断参数是否为整数
if (!Character.isDigit(args.charAt(i))) {
return false;
}
}
return true;
}
public static void main(String[] args) {// String args[ ]或者String[ ] args表示给主方法传一个字符串数组. 而args是一个字符串数组的变量名,不是关键字
// TODO Auto-generated method stub
// Custom customer = new Custom();
// Scanner input = new Scanner(System.in);
// int input1 = input.nextInt();// 输入两个整数;
// int input2 = input.nextInt();
// 右鍵》Run As》Run Configuration》Arguments》在Program arguments 下方框输入两个数;
try {
if (args.length != 2) {// 判断字符个数
throw new ParameterNumberException();
} else {
if (!check(args[0]) || !check(args[1])) {// 判断字符格式
throw new ParameterFormateException();
}
}
} catch (ParameterNumberException e) {
System.out.println(e.warnMess());// 打印 参数个数异常
e.printStackTrace();// 在命令行打印异常信息在程序中出错的位置及原因
} catch (ParameterFormateException e) {
System.out.println(e.warnMess());// 打印参数格式异常
e.printStackTrace();// 在命令行打印异常信息在程序中出错的位置及原因
}
}
}
ParameterFormateException.java
public class ParameterFormateException extends Exception {
String message;
public ParameterFormateException() {
message = "参数格式异常";
}
public String warnMess() {
return message;
}
}
ParameterNumberException.java
public class ParameterNumberException extends Exception {
String message;
public ParameterNumberException() {
message = "参数个数异常";
}
public String warnMess() {
return message;
}
}
命令行获取整数
运行结果图
2)编写一个异常类MyException,在编写一个类Student,该类有一个产生异常的方法public void speak(int m)throws MyException,要求参数m的值大于1000时,方法抛出一个MyException对象。最后编写一个主类,在主类的main方法中用Student创建一个对象,让该对象调用speak方法。
MyException.java
public class MyException extends Exception {
String message;
public MyException() {
message = "m的值大于1000";
}
public String seeView() {
return message;
}
}
Student.java
public class Student {
public void speak(int m) throws MyException {
if (m > 1000) {
throw new MyException();
}
}
}
MainClass.java
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student student = new Student();
try {
student.speak(999);
student.speak(1001);
} catch (MyException e) {
System.out.println(e.seeView());
e.printStackTrace();
}
}
}