异常在java中是很常见的,也是可以直接进行处理的.主要分为受检异常和运行时异常.
受检异常的捕获是按照子类和父类的先后顺序进行的,而运行时异常也是如此,只是更加灵活而已.
1 受检异常
调试的代码为:
package com.company;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main1 {
public static void main(String[] args) {
try {
throw new FileNotFoundException();
} catch (IOException ioe) {
System.out.println("catched the IOException 1");
}
try {
throw new FileNotFoundException();
} catch (FileNotFoundException fnfe) {
System.out.println("catched the FileNotFoundException");
}
try {
m();
} catch (FileNotFoundException fnfe) {
System.out.println("catched the FileNotFoundException in m");
} catch (IOException ioe) {
System.out.println("catched the IOException in m");
} catch (Throwable t) {
System.out.println("catched the Throwable in m");
}
}
static void m() throws IOException {
throw new FileNotFoundException();
}
}
运行结果为:
可以看到,在捕获到子类的异常后,父类的异常就直接跳过不再捕获了.
2 运行时异常
调试的代码为:
package com.company;
class TestException extends Exception {
TestException() { super(); }
TestException(String s) { super(s); }
}
public class Main {
public static void main(String[] args) {
for (String arg : args) {
try {
thrower(arg);
System.out.println("Test \"" + arg +
"\" didn't throw an exception");
} catch (Exception e) {
System.out.println("Test \"" + arg +
"\" threw a " + e.getClass() +
"\n with message: " +
e.getMessage());
}
}
}
static int thrower(String s) throws TestException {
try {
if (s.equals("divide")) {
int i = 0;
return i/i;
}
if (s.equals("null")) {
s = null;
return s.length();
}
if (s.equals("test")) {
throw new TestException("Test message");
}
return 0;
} finally {
System.out.println("[thrower(\"" + s + "\") done]");
}
}
}
运行结果很简单,这里不再给出,可自行测试.
3 小节
异常的捕获首先会处理子类异常,如果子类异常已被捕获,那么父类异常就会跳过.如果直接捕获父类异常,则所有的子类异常都将跳过,这肯定是很粗糙的处理方式,应该避免.