异常处理
异常处理常见手段: try catch finally throws
1.try catch
1.将可能抛出FileNotFoundException 文件不存在异常的代码放在try里
2.如果文件存在,就会顺序往下执行,并且不执行catch块中的代码
3. 如果文件不存在,try 里的代码会立即终止,程序流程会运行到对应的catch块中
4. e.printStackTrace(); 会打印出方法的调用痕迹,
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class rubbish {
public static void main(String args[]){
File f= new File("d:/LOL.exe");
try{
System.out.println("试图打开 d:/LOL.exe");
new FileInputStream(f);
System.out.println("成功打开");
}
catch(FileNotFoundException e){
System.out.println("d:/LOL.exe不存在");
e.printStackTrace();
}
}
}
2.使用异常的父类进行catch
FileNotFoundException是Exception的子类,使用Exception也可以catch住FileNotFoundException
例如在上面的代码中,在catch的参数中,用Exception代替FileNotFoundException
3.多异常捕捉办法
有的时候一段代码会抛出多种异常,解决办法之一就是写多个catch
下面的代码执行之后,只能捕捉到文件异常,文件异常的代码写在前面,执行完文件异常的代码之后,其他代码就不会被执行了。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class rubbish {
public static void main(String args[]){
File f = new File("d:/LOL.exe");
try {
//文件异常代码
System.out.println("试图打开 d:/LOL.exe");
new FileInputStream(f);
System.out.println("成功打开");
//日期异常的代码
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = sdf.parse("2016/06-03");
} catch (FileNotFoundException | ParseException e) {
if (e instanceof FileNotFoundException)
System.out.println("d:/LOL.exe不存在");
if (e instanceof ParseException)
System.out.println("日期格式解析错误");
e.printStackTrace();
}
}
}
4.finally
无论是否出现异常,finally中的代码都会被执行
5.throws
throws:把异常抛给上一个函数
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class rubbish {
public static void main(String[] args) {
method1();
}
private static void method1() {
try {
method2();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void method2() throws FileNotFoundException {
File f = new File("d:/LOL.exe");
System.out.println("试图打开 d:/LOL.exe");
new FileInputStream(f);
System.out.println("成功打开");
}
}
throw和throws的区别
throws与throw这两个关键字接近,不过意义不一样,有如下区别:
- throws 出现在方法声明上,而throw通常都出现在方法体内。
- throws 表示出现异常的一种可能性,并不一定会发生这些异常;throw则是抛出了异常,执行throw则一定抛出了某个异常对象。
6.练习
假设有一个方法 public int method(), 会返回一个整数
在这个方法中有try catch 和 finally.
try 里返回 1
catch 里 返回 2
finally 里 返回3
那么,这个方法到底返回多少?
对练习的理解:
其实在try中遇到return后,系统会将return的值保存在一个区域中,然后如果有finally就执行finally里的代码,如果又遇到了return,就会将最后这个return值覆盖原来的那个值,在返回给调用者
package pack6;
public class Except {
static public int method(){
try {
return 1;
}catch (Exception e){
return 2;
}finally {
return 3;
}
}
static public void main(String args[]){
System.out.println(method());//返回3
}
}