Java 7之异常第一篇

来源:互联网 发布:彬哥破解软件 编辑:程序博客网 时间:2024/06/05 05:17

Java异常面试题目:

public class TestExceptionFlow {// FileNotFoundException extends IOExeptionpublic static void main(String args[]) {try {throw new java.io.FileNotFoundException();} catch (java.io.IOException oe) {// throw new IllegalArgumentException(); 放到这里时有编译错误,下面的语句不可达System.out.println("IOException");throw new IllegalArgumentException(); // 直接抛出异常,下面的并不会捕获} catch (IllegalArgumentException ie) {System.out.println("IllegalArgumentException");return;} catch (Exception e) {System.out.println("Exception");return;} finally {System.out.println("finnaly");}}}
输出的结果如下:

Exception in thread "main" java.lang.IllegalArgumentExceptionat com.javabase.exception.TestExceptionFlow.main(TestExceptionFlow.java:9)IOExceptionfinnaly

Java异常机制可以使程序中异常处理代码和正常业务代码分离,保证程序代码更加优雅,并提高程序健壮性。

Java异常需要掌握的关键字:try、catch、finally、throw、throws。


  1.  try        -- 将可能抛出异常的代码放在try语句块之内,当try语句块内发生异常时,异常就被抛出。
  2.  catch   -- 用于捕获异常。catch用来捕获try语句块中发生的异常。
  3.  finally  -- finally语句块总是会被执行。它主要用于回收在try块里打开的资源(如数据库连接、网络连接和磁盘文件)。只有finally块执行完成之后,才会回来执行try或者catch块中的return或者throw语句,如果finally中使用了return或者throw等终止方法的语句,则就不会跳回执行,直接停止。
  4.  throw   -- 用于抛出异常。
  5.  throws -- 用在方法上,用于声明该方法可能抛出的异常。

关于finally的例子,可以参见:
传送门:http://blog.csdn.net/mazhimazh/article/details/17754877

在实际工作中,Java异常是需要好好处理的。所以可以继承Exception来招出自己的异常。举例:
public class NotExistResourceException extends Exception {private static final long serialVersionUID = 5987424525387592772L;public NotExistResourceException(){      super();    }public NotExistResourceException(String error){       super(error);     }}
public class TestException {    public static void main(String args[]) throws NotExistResourceException{    File file = new File("C:\\a.txt");    if(!file.exists()){    throw new NotExistResourceException("file not exist");    }    }}
运行后抛出的主要异常信息如下:
Exception in thread "main" TestException.NotExistResourceException: file not exist

或者还可以如下这样做:
public byte[] convert(Object source) {ByteArrayOutputStream byteStream = new ByteArrayOutputStream(256);try  {this.serializer.serialize(source, byteStream);return byteStream.toByteArray();}catch (Throwable ex) {throw new SerializationFailedException("Failed to serialize object using " +this.serializer.getClass().getSimpleName(), ex);}}
在catch()中招出自定义的异常,这样就不用在父类中进行重新捕获处理了(convert方法上没有throws异常,父类感知不到)


在了解异常体系时,需要了解的主要类如下:

1. Throwable
  
Throwable是 Java 语言中所有错误或异常的超类。包含两个子类: Error 和 Exception。
  Throwable包含了其线程创建时线程执行堆栈的快照,所以可以在catch语句块中使用e.printStackTrace()打印异常信息。但是如果要进行日志记录,则最好使用e.fillInStackTrace()存储堆栈快照。

2. Exception

  Exception及其子类是 Throwable 的一种形式,它指出了合理的应用程序想要捕获的条件。

3. RuntimeException 
 
 RuntimeException是那些可能在 Java 虚拟机正常运行期间抛出的异常的超类。
  编译器不会检查RuntimeException异常。例如,除数为零时,抛出ArithmeticException异常。字符串为空时,抛出NullPointerException异常。如下程序在编译时不会报错:

HashMap<String,String> map = new HashMap<String,String>();// map.get("xx")值为 nullmap.get("xx").trim();

       RuntimeException是NullPointerException的超类。如上代码没有通过throws声明抛出NullPointerException异常",也没有通过try...catch...处理这个异常,也能通过编译。也就说明编译器不会检查RuntimeException异常
      所以在编写代码时要特别注意这些异常的处理。例如,如上的程序就可以先进行判空操作。

4. Error
  
和Exception一样,Error也是Throwable的子类。它用于指示合理的应用程序不应该试图捕获的严重问题,大多数这样的错误都是异常条件。
  和RuntimeException一样,编译器也不会检查Error。














0 0
原创粉丝点击