1.异常(Throwable):程序在执行过程中,因为程序员的疏忽或者是外在环境的因素,可能使得程序在执行时产生错误,造成计算结果的不正确.异常又分为:Error和Exception,Error通常是一些很严重,灾难性的错误,如内存不足等等.而Exception中又含有了许多异常,如Runtime Expection等等.而这些异常大部分在编程的时候是可以预防的.
2.捕捉和处理异常:
1). try...catch
try就是"尝试"的去执行某些程序代码,当这些程序代码中有异常的时候,把异常给"捕捉"(catch)下来,因此我们可以把可能会产生异常的代码写在try的语句块中.要捕捉什么样的异常,就使用catch把它捕捉下来.通常其格式为:
try { } catch (Exception ef) { ef.printStackTrace(); }
2). throws关键字
当异常产生的时候,我们可以不必马上去处理它,可以将异常抛出,而这个异常将会抛给调用这个可能会产生异常的方法的方法,一直这样抛出,直到抛给主函数,之后主函数又会抛给java虚拟机.
public static void main(String args[]) throws Exception{ String path = "D:\\a.txt"; String path1 = "D:\\aa.txt"; FileTest ft = new FileTest(); // 读取数据 String str = ft.readFile(path); System.out.println(str); // 将数据写到文件 ft.writeFile(path1, str); } public void writeFile(String path, String content) throws Exception{ // 创建一个文件输出流,如果文件不存在,会自动创建一个文件 java.io.FileOutputStream fos = new java.io.FileOutputStream(path); // 将字符串转成字节数组 byte[] bs = content.getBytes(); // 遍历数组,取出字节,写到流中 for (int i = 0; i < bs.length; i++) { // 写出字节 fos.write(bs[i]); } // 强制输出 fos.flush(); // 关闭流 fos.close(); }
3).自定义异常
我们在设计自己的类的时候,有时候也需要产生异常,用来规范用户的一些操作.
/** * 异常机制 * @author Administrator * */ public class ExceptionTest { public static void main(String args[]) throws Exception{ ExceptionTest et = new ExceptionTest(); et.change(120);//超出了自定义的数字的范围.产生异常 } /** * 自定义异常:数字的范围必须在0~100 * @param num * @throws Exception */ public void change(int num) throws Exception{ if(num>=0&&num<=100){ System.out.println("正确.."); }else{ //创建一个异常对象 Exception ef = new Exception("传入的数据不符合要求!!"); //抛出异常对象 throw ef; } } }