众所周知,我们在使用一个程序的时候,当我们的输入不符合要求的时候,我们并不希望程序直接抛出一个异常,就停止了。而是希望程序可以给出一个优雅的提示,并且继续运行,这样就显得比较优雅,因此我们需要在代码上多下点功夫。
下面来举个例子(输入以文件的形式进行)
我们读入文件,希望用正则表达式匹配出符合要求的字串,然后继续执行程序。
然而,有些文件是不合法的,这时我们希望程序不会因为不合法的输入停止运行。
我们在程序中对于一些不合法的输入throw 出异常,这时通用的做法,但是这样是不够的(不用在意我的程序是什么意思,我只是讲异常处理的方法)
if (!m1.find() && flag1 != 1) {
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
if (Character.isDigit(ch)) {
throw new Rexception();
}
}
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
if (Character.isLetter(ch)) {
if (Character.isLowerCase(ch)) {
lowercase++;
}
if (Character.isUpperCase(ch)) {
uppercase++;
}
}
if (lowercase > 1) {
throw new LCexception();
}
}
}
异常类我这样定义,实际上直接继承一下父类就可以了,这里我定义了创建类的两种方式。
public class FEexception extends Exception {
private static final long serialVersionUID = 1L;
public FEexception() {
System.out.println("shoule use scientific notation but not");
}
public FEexception(String message) {
super(message);
}
}
main函数这样写
public static void main(String[] args)
throws IOException, Lessexception, LCexception, Moreexception, Rexception {
AtomStructureCia systemcia = new AtomStructureCia();
String[] nameOfFileStrings = {"AtomicStructureless.txt", "AtomicStructuremore.txt",
"AtomicStructurereverse.txt", "AtomicStructurerb.txt", "AtomicStructure.txt"};
for (int i = 0; i < 5; i++) {
System.out.print(i + 1);
try {
GuiAtomStructure systemAtomStructure = new GuiAtomStructure();
systemAtomStructure.visualize(systemcia.readfile(nameOfFileStrings[i]));
} catch (IOException e) {
e.printStackTrace();
} catch (Lessexception e) {
System.out.println("not enough information");
} catch (LCexception e) {
System.out.println("Illegal letter");
} catch (Moreexception e) {
System.out.println("the information is over flow");
} catch (Rexception e) {
System.out.println("the information has a wrong order");
}
}
在调用函数后(第一个代码片段就是readfile函数的部分代码),如果检测出函数抛出异常,就把它catch住,然后接着执行程序,程序不会终止。
异常类会处理这些异常,而异常却是输入错误导致的。
再次声明,本片博客讲的是如何进行异常处理,讲的是异常如何产生的以及处理的方法,这些函数不是重点。