try{
代码块1;
}catch(XXException e){
代码块2
}
这是基础的异常处理语法定义
代码块1里面写的是有可能报错的代码,
XXException是有可能出现的错误,若是出了此种错误便会执行catch{}里的代码,若不是此种类型的错误,就不会走这个catch{}
常见的错误有:
空指针异常类:NullPointerException
类型强制转换异常:ClassCastException
数组负下标异常:NegativeArrayException
数组下标越界异常:ArrayIndexOutOfBoundsException
包含所有错误:Exception
等等,可以自行搜索java常见的异常和错误
System.out.println("程序开始");
try{
String str = "a";
System.out.println(str.length());
System.out.println(str.charAt(0));
System.out.println(Integer.parseInt(str));
}catch(NullPointerException e){
System.out.println("空指针");
}catch(StringIndexOutOfBoundsException e){
System.out.println("字符串下标越界了");
/*
* 在最后一个catch处理Exception,可以避免因为一个未捕获的异常导致
* 程序中断
*/
}catch(Exception e){
System.out.println("反正出了个错");
}
/*
* 可以定义多个catch,当不同的异常我们有不同的处理手段,
* 可以分别捕获这些,异常处理机制
*/
System.out.println("程序结束");
}
在这个程序中,字符串“a”,长度为1,str[0]是a,但是它不能转成二进制。所以会走最后一个Exception异常。
如果str=null;那么应该报空指针异常。
如果str=" ";那么应该报数组下标越界异常
但是在有些时候,我们程序必须要执行某些语句(比如流读写操作中,必须要关闭流)此时我们需要用到一个关键字finally
一个小栗子
System.out.println("程序开始");
try{
String str = "a";
System.out.println(str.length());
return;//写了return,下面语句都不会执行,除了finally块
}catch(Exception e){
System.out.println("程序出了个错,不知道啥错");
}finally{
System.out.println("finally块一定会执行");
}
System.out.println("程序结束");
关闭文件流的例子
FileOutputStream fos = null;
try {
fos = new FileOutputStream("fos.dat");
} catch (FileNotFoundException e) {
System.out.println("出错了");
}finally{
try {
if(fos!=null){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
在关闭流这个操作中,java的jdk7以上版本有自动关闭特性,即把代码写在try()内,在程序结束时,try()中的语句会自动关闭流。所以上面的代码可以简写为:
try(
FileOutputStream fos = new FileOutputStream("test.txt");
){
fos.write(1);
} catch (Exception e) {
System.out.println("出错了");
}
}
值得注意的是:只有实现Closeable接口的类才能写在try里面,会自动关闭,不需要写close()方法。一般流的类都实现Closeable的接口了,没有实现Closeable接口的写在try中会报错。