软件构造 lab4-Debugging, Exception Handling, and Defensive Programming
1 实验目标概述
本次实验重点训练学生面向健壮性和正确性的编程技能,利用错误和异常处理、断言与防御式编程技术、日志/断点等调试技术、黑盒测试编程技术,使程序可在不同的健壮性/正确性需求下能恰当的处理各种例外与错误情况,在出错后可优雅的退出或继续执行,发现错误之后可有效的定位错误并做出修改。
实验针对 Lab 3 中写好的 ADT 代码和基于该 ADT 的三个应用的代码,使用以下技术进行改造,提高其健壮性和正确性:
错误处理
异常处理
Assertion 和防御式编程
日志
调试技术
黑盒测试及代码覆盖度
2 实验环境配置
略
3 实验过程
请仔细对照实验手册,针对每一项任务,在下面各节中记录你的实验过程、阐述你的设计思路和问题求解思路,可辅之以示意图或关键源代码加以说明(但千万不要把你的源代码全部粘贴过来!)。
3.1 Error and Exception Handling
3.1.1 处理输入文本中的三类错误
3.1.1.1 不符合语法规范错误
3.1.1.1.1 DataPatternException
正则表达式时由于数据的常量错误而没有匹配到单个元素
if (!matcher.find())
{
try {
throw new DataPatternException(“数据:\n” + stringInfo + " \n不符合输入规范!"); //正则表达式是否能够匹配
} catch (DataPatternException e) {
flightlogger.log(Level.SEVERE, e.getMessage(), e); //日志
throw new DataPatternException(“数据:\n” + stringInfo + " \n不符合输入规范!");
}
}
3.1.1.1.2 EntryNumberFormatException
计划项编号不符合规则
public static void checkEntryNumber(String planningEntryNumber) throws EntryNumberFormatException
{
if(Character.isUpperCase(planningEntryNumber.charAt(0)) && Character.isUpperCase(planningEntryNumber.charAt(1)))
{
for(int i = 2; i < planningEntryNumber.length(); i++)
{
if(!Character.isDigit(planningEntryNumber.charAt(i)))
throw new EntryNumberFormatException("航班号 " + planningEntryNumber + " 格式错误!");
}
}
else
throw new EntryNumberFormatException("航班号 " + planningEntryNumber + " 格式错误!");
}
3.1.1.1.3 SameAirportException
起飞和到达机场相同引起的错误
public static void checkAirport(String location1, String location2) throws SameAirportException
{
if (location1.equals(location2))
{
throw new SameAirportException(location1 + ": 起始机场与降落机场相同!");
}
}
3.1.1.1.4 TimeOrderException
起飞时间应该在到达时间之前(不能相等)
public static void checkTime(String departureTime, String arrivalTime) throws TimeOrderException {
LocalDateTime dt = null, at = null;
try {
dt = LocalDateTime.parse(departureTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
at = LocalDateTime.parse(arrivalTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
} catch (Exception e) {
throw new DateTimeParseException("输入时间不符合规范!", departureTime + arrivalTime, 0);
} finally {
if(dt != null && at != null)
{
if (!dt.isBefore(at))
throw new TimeOrderException("起飞时间 " + departureTime + " 不在降落时间 " + arrivalTime + " 之前.");
}
}
}
3.1.1.1.5 PlaneNumberFormatException
飞机编号不符合格式。
public static void checkPlaneNumber(String planeNumber) throws PlaneNumberFormatException
{
if(planeNumber.charAt(0) == 'N' || planeNumber.charAt(0) == 'B')
{
for(int i = 1; i < planeNumber.length(); i++)
{
if(!Character.isDigit(planeNumber.charAt(i)))
throw new PlaneNumberFormatException("飞机编号:" + planeNumber + " 格式错误!");
}
}
else
throw new PlaneNumberFormatException("飞机编号:" + planeNumber + " 格式错误!");
}
3.1.1.1.6 PlaneTypeException
飞机类型不符合格式
public static void checkPlaneType(String planeType) throws PlaneTypeException
{
for(int i = 0; i < planeType.length(); i++)
{
if(!Character.isDigit(planeType.charAt(i)) && !Character.isUpperCase(planeType.char