异常处理
1、IO文件不存在
import java.io.FileNotFoundException;
import java.io.FileReader;
public class TestError {
public static void main(String[] args) throws FileNotFoundException {
FileReader fr = new FileReader("D:\\aa.text");
}
}
2、就地解决异常
import java.io.FileNotFoundException;
import java.io.FileReader;
public class TestError {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("D:\\aa.text");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class TestError {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("D:\\aa.text");
Socket s = new Socket("192.168.1.1", 78);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class TestError {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("D:\\aa.text");
Socket s = new Socket("192.168.1.1", 78);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
如果抛出异常,那么就终止执行代码,
如何进入actch,如果有多个catch语句,则进入匹配那个。
一般把需要关闭的资源。[文件,连接。内存……]放在finally里面
import java.io.FileReader;
import java.net.Socket;
public class TestError {
public static void main(String[] args) {
FileReader fr = null;
try {
fr = new FileReader("D:\\aa.txt");
Socket s = new Socket("192.168.1.1", 78);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
System.out.println("finally");
if (fr != null) {
try {
fr.close();
} catch (Exception e2) {
e2.printStackTrace();
// TODO: handle exception
}
}
}
}
}
注意:finally不一定要放在catch后面,也可以直接放在try后面不要catch,但是不常见。
3、抛出异常
import java.io.FileNotFoundException;
import java.io.FileReader;
public class TestError {
public static void main(String[] args) <span style="color:#ff0000;"><strong>throws FileNotFoundException</strong></span> {
FileReader fr = new FileReader("D:\\aa.text");
}
}