IO流的异常处理方式
jdk7之前(较繁琐不推荐)
用try{}catch(){}
代替throw
(简单代码)
public static void main(String[] args) throws IOException //这里用throw抛出异常
{
FileOutputStream fos = new FileOutputStream("D:\\A.txt");
fos.write("abc".getBytes());
fos.close();
}
public static void main(String[] args) {
//用try{}catch(){}抛出异常
try{
FileOutputStream fos = new FileOutputStream("D:\\A.txt");
fos.write("abc".getBytes());
fos.close();
}catch (IOException e){
e.printStackTrace();
}
}
- 若是在 try 中加入另一个可以引发异常的代码,例如
try{
//引发ArithmeticException: / by zero算术运算异常
System.out.println(10 / 0);
FileOutputStream fos = new FileOutputStream("D:\\A.txt");
fos.write("abc".getBytes());
fos.close();
}catch (IOException e){
e.printStackTrace();
}
因为这个异常在close
前面,一旦报异常,close
将无法执行。所以字节输出流无法关闭。为了解决这一问题,我们可以将close
放到finally
中。
try{
System.out.println(10 / 0);
FileOutputStream fos = new FileOutputStream("D:\\A.txt");
fos.write("abc".getBytes());
}catch (IOException e){
e.printStackTrace();
}finally {
//这时fos会标红
//因为fos权限不够
//把fos提到上面
fos.close();
}
//虽然我们对fos赋值了,但发生异常时可能会无法执行
//所以我们先给他赋个null
//close还在标红 我们再给他抛个异常
FileOutputStream fos = null;
try{
System.out.println(10 / 0);
fos = new FileOutputStream("D:\\A.txt");
fos.write("abc".getBytes());
}catch (IOException e){
e.printStackTrace();
}finally {
try{
fos.close();
}catch (IOException e){
e.printStackTrace();
}
}
- 运行发现NullPointerException(fos确实是null)那么我们加个判断
try{
if (fos != null) {
fos.close();
}
}catch (IOException e){
e.printStackTrace();
}
正确代码
public class FileOutputStreamDemo1 {
public static void main(String[] args){
FileOutputStream fos = null;
try{
fos = new FileOutputStream("D:\\A.txt",true);
fos.write("您好您好".getBytes());
} catch (IOException e){
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
}
jdk7之后(推荐)
public static void main(String[] args) {
//将流对象直接放在try小括号里
try(FileOutputStream fos = new FileOutputStream("D:\\A.txt");){
fos.write("abc".getBytes());
}catch (IOException e){
e.printStackTrace();
}
}
格式:
try(需要调用close方法的对象){
逻辑代码
}catch(异常类名 对象名){
异常的处理方式
}
最后总结
这个怎么打断点,为啥不能调试,有同学知道吗?