异常处理
java.lang.Throwable
Error 错误 程序中不处理
Exception 异常 ,在编写程序时,要考虑对这些异常的处理
异常分为编译时异常、运行时异常 (RuntimeException)。
当执行一个程序时,如果出现异常,则异常之后的代码就不再执行
常见的运行时异常: 1、数组下标越界异常 2、算术异常 3、类型转化异常 4、空指针异常
1 public class TestException 2 { 3 @Test 4 public void test1(){ 5 int [] i=new int [10]; 6 System.out.println(i[10]); 7 } 8 9 @Test 10 public void test2(){ 11 System.out.println(1/0); 12 } 13 14 @Test 15 public void test3(){ 16 Object obj=new Date(); 17 String str=(String) obj; 18 } 19 20 @Test 21 public void test4(){ 22 Person p=new Person(); 23 p=null; 24 System.out.println(p.toString()); 25 } 26 }
java 提供的是异常处理的抓抛模型
1、抛 :当我们执行代码时,一旦出现异常,就会在异常的代码处生成一个对应的异常类型的对象,并将此对象抛出。一旦抛出此类型的对象,那么程序终止执行,此异常类的对象抛给方法的调用者。抛的方式有两种,一种是自动的,一种是手动的(throw)。
2、抓:抓住上一步抛出来的异常类的对象。java中提供了两种方式来处理一个异常类的对象。
处理方式一: try{
可能抛出异常的代码
}catch( exception e){
处理异常
} finally{
一定要执行的代码(可选)
}
若catch 多个异常类型,是并列关系,catch的顺序没有关系;若catch 的异常是包含关系,则范围小的(子类)一定要写在(父类)上面。
finally 中存放的是一定会执行的代码,不管catch中是否有异常或者return语句。
处理方式二:声明抛出异常
由方法的调用者负责处理,在方法声明中,显式地抛出该异常的类型。异常的对象可以逐层上抛,直到main方法中,在上抛的过程中,也可以通过try-catch-finally处理。
1 public class TestException2 2 { 3 public static void main(String[] args) 4 { 5 try 6 { 7 method1(); 8 } catch(FileNotFoundException ex){ 9 System.out.println(ex.getMessage()); 10 } 11 catch (IOException e) 12 { 13 System.out.println(e.getMessage()); 14 } 15 } 16 17 public static void method1() throws FileNotFoundException, IOException{ 18 FileInputStream fis=new FileInputStream(new File("hello.txt")); 19 int b; 20 while ((b=fis.read())!=-1){ 21 System.out.println(b); 22 } 23 fis.close(); 24 } 25 }
手动抛出(throw)的异常类型对象可以是现有的异常类型对象,也可以是自定义的异常类型(必须继承于Throwable)。
1 public class MyException extends RuntimeException 2 { 3 4 private static final long serialVersionUID = -7736287090372348682L; 5 6 public MyException(){ 7 8 } 9 10 public MyException(String msg){ 11 super(msg); 12 } 13 }

浙公网安备 33010602011771号