Exception的应用,一般表现在throws和try...catch
public class ExceptionTest {
public static void main(String[] args) {
writte();
}
private static void writte() {
BufferedOutputStream ops = null;
try {
ops = new BufferedOutputStream(new FileOutputStream("a.txt"));
byte[] b = "abcdef".getBytes();
ops.write(b);
} catch (FileNotFoundException e) {//对于可能出现的异常必须try...catch或者throws
throw new RuntimeException("读写异常");
} catch (IOException e) {
throw new RuntimeException("读写异常");
}finally{//finally子块一定会执行的操作,一般用来关闭资源
if(ops!=null)
try {
ops.close();
} catch (IOException e) {
throw new RuntimeException("读写异常");
}
}
}
如上例子对于可能出现的异常必须进行try...catch或者throws才可以编译通过。finally块里面的代码不管异常是否出现都会实现的,通常用来关闭资源。一般方法里面如果抛出异常的话,方法上须throws该异常,同时调用者也必须要捕获或抛出。该例子之所以没有,是因为抛出的是RuntimeException。
RuntimeException ,即运行时异常,是那些可能在 Java 虚拟机正常运行期间抛出的异常的超类。
可能在执行方法期间抛出但未被捕获的 RuntimeException 的任何子类都无需在 throws 子句中进行声明。
public class ExceptionTest {
public static void main(String[] args) {
int c = 4/0;
}
}
上面例子中会抛出ArithmeticException,但是程序并不用抛出或捕获就可以编译通过。ArithmeticException,是RuntimeException的子类,
而不抛出或捕获则是运行时异常的特点之一。而且异常一旦抛出,程序立即中断,后面的内容都不会运行。这可以提醒程序员修改一些重大的错误。
当自定义异常时,如果该异常的发生,使得程序无法再继续进行运算,就让自定义异常继承RuntimeException。