基本语法
try catch throw
try {
process1();
} catch (Exception e) {
e.printStackTrace(); //打印异常栈
}
如果不想在函数中捕获异常,可以加上throws把它转交给调用方处理;
最后一层层扔到了main,若连main也不想处理,可以继续throw,这就真的丢弃了。这时一旦出错直接程序崩溃。
public class Main {
public static void main(String[] args) throws Exception {
byte[] bs = toGBK("中文");
System.out.println(Arrays.toString(bs));
}
static byte[] toGBK(String s) throws UnsupportedEncodingException {
// 用指定编码转换String为byte[]:
return s.getBytes("GBK");
}
}
捕获多种异常
catch会依次执行,需要将子类放到前面,否则总会落到父类里去,正确做法如下:
public static void main(String[] args) {
try {
process1();
process2();
process3();
} catch (UnsupportedEncodingException e) {
//IOException的子类
System.out.println("Bad encoding");
} catch (IOException e) {
System.out.println("IO error");
}
}
若两种异常没有继承关系,可以用|
连接:
public static void main(String[] args) {
try {
process1