Java异常机制

来源:互联网 发布:vs2010c 数据库教程 编辑:程序博客网 时间:2024/06/05 02:14

try-catch-finally:

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
 * 测试try catch
 * @author 30869
 *如果try_catch_finally语句块里面都有返回值,执行顺序为:先执行try_catch_finally,再给返回值赋值,再返回,
 *如果finally里面没有返回值,则返回报异常的catch语句里的返回值,如果没报异常,则返回try语句块的返回值,
 *finally一般不要加return语句
 */
public class Try_catch_finally_readFile {


public static void main(String[] args) {
FileReader fileReader = null;//将声明放在try语句块外面,finally才能读取到
try {
fileReader = new FileReader("G:/JavaTry_catch_Test.txt");//创建一个读取文件的对象
char c = (char) fileReader.read();//按字符读取
char c2 = (char) fileReader.read();
System.out.println(""+c+c2);
System.out.println(c+""+c2);
} catch (FileNotFoundException e) {//会抛出文件不存在异常
e.printStackTrace();
} catch (IOException e) {//会抛出IO流异常
e.printStackTrace();
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e) {//会抛出IO流异常
e.printStackTrace();
}
}
}
}


}


throw:

import java.io.File;
import java.io.FileNotFoundException;
/**
 * Throw的用法
 * @author 30869
 *
 */
public class Throw {


public static void main(String[] args) {
File file=new File("JavaTry_catch_Test.tx");
if(!file.exists()){
try {
throw new FileNotFoundException("文件不存在");//手动创建异常对象,并抛出
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}


}


throws:

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
 * Throws的用法
 * @author 30869
 * 注意:子类重写父类的方法是,抛出的异常不能大于父类异常的范围,种类不能多于父类的异常种类
 */
public class Throws {


public static void main(String[] args) {
try {
char c=openFile("G:/JavaTry_catch_Test.txt");
System.out.println(c);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static char openFile(String dir) throws FileNotFoundException,IOException{//声明抛出异常,由调用者处理
FileReader fileReader=new FileReader(dir);
char c=(char)fileReader.read();
fileReader.close();
return c;
}
}

原创粉丝点击