1 try-catch 语句
基本与 C++ 中的一致。
public static void main(String args[]) {
try {
BufferedReader in = new BufferedReader(System.in));
System.out.print("Please input a number: ");
String s = in.readLine();
int n = Integer.parseInt(s);
} catch (IOException ex) {
ex.printStackTrace();
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
}
运行时系统在调用栈中查找,从生成异常的方法开始进行回溯,直到找到
catch
语句的代码。
1.1 抛出异常
throw 异常对象;
1.2 捕获异常
try {
// ...
} catch (异常类名 异常形参) { // 可选
// ...
} catch (异常类名 异常形参) {
// ...
} finally { // 可选
}
1.3 异常的分类
Throwable
Error
: JVM 错误Exception
: 异常一般所说的异常是指
Exception
及其子类
1.3.1 Exception 类
- 构造方法
public Exception();
public Exception(String message);
Exception(String message, Throwable cause);
- 方法
getMessage()
getCause()
printStackTrace()
1.3.2 多异常的处理
下面这个例子展示了 finally
的情况。
public class TestTryFinally {
static String output = "output ";
public static void main(String args[]) {
foo(1);
System.out.println(output);
}
public static void foo(int i) {
try {
if (i == 1) {
throw new Exception();
}
output += "1";
} catch (Exception e) {
output += "2";
return;
} finally {
output += "3";
}
}
}
// 输出结果
// output 23
1.3.3 受检的异常
RuntimeException
异常可以直接使用if
语句处理。main
函数也可以写throws
下面是 throws
的例子:
import java.io.*;
public class TestTryThrowsToOther {
public static void main(String args[]) {
try {
System.out.println("======Before======");
readFile();
System.out.println("======After=======");
} catch (IOException e) {
System.out.println(e);
}
}
public static void readFile() throws IOException {
FileInputStream in = new FileInputStream("test.txt");
int b;
b = in.read();
while (b != -1) {
System.out.print((char) b);
b = in.read();
}
in.close();
}
}
1.4 try-with-resource
try ( 类型 变量名 = new 类型 () ) {
// ...
}
// 相当于自动添加了 finally { 变量.close(); }
// 当然,变量必须是 Closable 的
2 自定义异常
重抛异常以及异常链接
下面是关于异常链接(多层异常)的例子:
import java.io.*;
public class hello {
public static void main(String args[]) {
try {
BankATM.getBalanceInfo(12345L);
} catch (Exception e) {
System.out.println("something wrong: " + e);
System.out.println("cause: " + e.getCause());
}
}
}
class DataHouse {
public static void findData(long id) throws DataHouseException {
if (id > 0 && id < 1000)
System.out.println("id: " + id);
else
throw new DataHouseException("cannot find the id");
}
}
class BankATM {
public static void getBalanceInfo(long id) throws MyAppException {
try {
DataHouse.findData(id);
} catch (DataHouseException e) {
throw new MyAppException("invalid id", e);
}
}
}
class DataHouseException extends Exception {
public DataHouseException(String message) {
super(message);
}
}
class MyAppException extends Exception {
public MyAppException(String message) {
super(message);
}
public MyAppException(String message, Exception cause) {
super(message, cause);
}
}
// 输出结果
// something wrong: MyAppException: invalid id
// cause: DataHouseException: cannot find the id