1.计算机运行时的错误
在计算机程序运行的过程中,错误总会出现:
- 用户输入错误
- 读写文件错误
- 网络错误,内存耗尽,无法连接打印机....
//假设用户输入了abc
String s = "abc";
int n = Integer.parseInt(s);//Error!
//用户删除了该文件
String t = readFile("C:\\abc.txt");//Error!
错误
如果方法调用出错,调用方如何得知这个错误:
- 约定返回错误码
int code = processFile("C:\\test.txt");
if (code==0) {
//ok:
}else{
//error:
switch(code){
case 1:
//file not found:
case 2:
//no read permission:
default:
//unknown error:
}
}
异常
java使用异常来表示错误:
- 异常是class,本身带有类型信息
- 异常可以在任何地方抛出
- 异常只需要在上层捕获,和方法调用隔离
try {
String s = processFile("C:\\test.txt");
//ok:
}catch (FileNotFoundException e) {
//file not found:
}catch (SecurityException e) {
//no read permission:
}catch (IOException e) {
//io error:
}catch (Exception e) {
//other error:
}
2.Java的异常体系
Java的异常也是class
- Throwable
- Error
- Exception
- RuntimeException
必须捕获的异常
- Exception及其子类,但不包括RuntimeException及其子类
- 称为Checked Exception
不需要捕获的异常
- Error及其子类
- RuntimeException及其子类
- Error是发生了严重的错误,程序对此一般无能为力:OutOfMemoryError,NoClassDefFoundError,StackOverflowError...
- Exception是发生了运行时逻辑错误,应该捕获异常并处理:
- 捕获并处理错误:IOException,NumberFormatException....
- 修复程序:NullPointerException,IndexOutOfBoundsException...
3.捕获异常
public static void main(String[] args){
try{
process1();
process2();
process3();
}catch (IOException e) {
System.out.println(e);
}
}
try{...} catch(){...}
- 使用try...catch捕获异常
- 可能发生异常的语句放在try{...}中
- 使用catch捕获对应的Exception及其子类
4.申明异常
static byte[] toGBK(String s) {
try{
return s.getBytes("GBK");
}catch (UnsupportedEncodingException e) {
System.out.println(e);
}
}
对可能抛出Checked Exception的方法调用:
- 捕获Exception并处理
- 不捕获但通过throws声明
- 通过throws声明仍需在上层捕获
- main()是最后捕获Exception的机会
若不捕获该异常,则需要申明该异常
static byte[] toGBK(String s) {
throws UnsupportedEncodingException {
return s.getBytes("GBK");
}
}
public static void main(String[] args){
try{
byte[] data = toGBK("test");
}catch (UnsupportedEncodingException e) {
System.out.println(e);
}
}
public class Main {
public static void main(String[] args){
test("UTF-8");
test("ABC");
}
static void test(String encoding) {
System.out.print("Test encoding " + encoding + "...");
try {
"test".getBytes(encoding);
System.out.println(" ok.");
} catch (UnsupportedEncodingException e) {
// TODO: handle exception
System.out.println(" failed.");
System.out.println(e);
}
}
}
总结
- Java使用异常来表示错误,并且使用try{...} catch{...}捕获异常
- Java的异常是class,并且从Throwable继承
- Error是无需捕获的严重错误
- Exception是应该捕获的可处理的错误
- RuntimeException无需强制捕获,非RuntimeException(Checked Exception)需强制捕获,或者使用throws声明