您的位置:首页 > 编程语言 > Java开发

[2014-10-22]JAVA笔记_Exception(异常)

2014-10-22 17:54 323 查看
一、 Java中的异常分为两大类

          1. Checked exception(非 Runtime exception):

          2. Unchecked exception(Runtime exception):

·Java 中所有的异常类都会直接或间接地继承自 Exception。

·RuntimeException类也是直接继承自 Exception类,它叫做运行时异常,Java中所有的运行时异常都会直接或间接地继承自RuntimeException。

·Java中凡是继承自 Exception 而不是继承自 RuntimeException 的类都是非运行时异常。

二、 异常处理的一般结构是:

         try{}catch(Exception e){}finally{}          无论程序是否出现异常,finally块中的代码都是会被执行的。

package com.bob.exception;

public class ExceptionTest2 {

public void method() throws Exception{
System.out.println("hello world.");

throw new Exception();		//抛出异常
}

public static void main(String[] args){

ExceptionTest2 test = new ExceptionTest2();

try{
test.method();		//捕获抛出的异常
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println("welcome");
}

}

}
        ·对于非运行时异常(checked exception),必须要对其进行处理,处理方式有两种:第一种是使用try...catch..finally进行捕获;第二种是在调用该会产生异常的方法所在的方法声明 throws Exception(相当于继续往上抛直到main方法,如果main方法也不处理那么就由JVM进行处理)。

        ·对于运行时异常(runtime exception),我们可以不对其进行处理,也可以对其进行处理。推荐不对其进行处理。

package com.bob.exception;

public class ExceptionTest3 {

public static void main(String[] args) {
String str = null;

System.out.println(str.length());

}

}
上面的程序会报NullPointerException异常。

NullPointerException 是空指针异常,出现该异常的原因在于某个引用为null,但你却调用了它的某个方法。这时就会出现该异常。

三、 自定义异常

         所谓自定义异常,通常就是定义了一个继承自Exception类的子类,那么这个类就是一个自定义异常类。通话情况下,我们都会直接继承自 Exception 类,一般不会继承某个运行时的异常类。

package com.bob.exception;

public class MyException extends Exception {

public MyException(){
super();
}

public MyException(String message){
super(message);
}

}
package com.bob.exception;

public class MyExceptionTest {

public void method(String str) throws Exception{

if(null == str){
throw new MyException("传入的字符串参数不能为null");
}else{
System.out.println(str);
}

}

public static void main(String[] args) {

MyExceptionTest test = new MyExceptionTest();

try{
test.method(null);
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println("异常处理完毕");
}

System.out.println("程序执行完毕");
}

}

·我们可以使用多个 catch 块来捕获异常,这时需要将父类型的 catch 块放到子类型的 catch 块之后,这样才能保证后续的 catch 可能被执行,否则子类型的 catch 将永远无法到达,java 编译器会报编译错误;如果多个catch块的异常类是独立的(MyException, MyException2),那么谁前谁后都是可以的。

package com.bob.exception;

public class ExceptionTest5 {

public void method(){
try{

System.out.println("进入到了try");

// return ; //会先执行finally然后return
System.exit(0); //退出虚拟机。finally不执行

}
catch(Exception e){

System.out.println("异常发生了");
}
finally{

System.out.println("进入到finally块");
}

System.out.println("异常处理后续的代码");
}

public static void main(String[] args) {

ExceptionTest5 test = new ExceptionTest5();

test.method();
}

}
备注:1. 如果 try 块中存在 return 语句,那么首先也需要将 finally 块中的代码执行完毕,然后方法再返回。
            2. 如果 try 块中存在 System.exit(0) 语句,那么就不会执行 finally 块中的代码,因为System.exit(0) 会终止当前运行的 Java 虚拟机,程序会在虚拟机终止前结束执行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  exception 异常