异常处理的原则:
1. 函数内容如果抛出需要检测的异常,那么函数上必须要声明。 否则,必须在函数内用try/catch捕捉,否则编译失败。
2. 如果调用到了声明异常的函数,要么try/catch,要么throws,否则编译失败。
3. 什么时候catch,什么时候throws呢? 功能内容可以解决,用catch。
解决不了,用throws告诉调用者,由调用者解决。
4. 一个功能如果抛出了多个异常,那么调用时,必须有对应多个catch进行针对性处理。
内部有几个需要检测的异常,就抛几个异常,抛出几个,就catch几个。
示例: 1. class Demo{
2. public int show(int index) throws ArrayIndexOutOfBoundsException{ 3. if(index < 0)
4. throw new ArrayIndexOutOfBoundsException(\"越界啦!\"); 5. int[] arr = new int[3]; 6. return arr[index]; 7. } 8. }
9.
10. class ExceptionDemo{
11. public static void main(String[] args){ 12. Demo d = new Demo(); 13. try{
14. int num = d.show(-3);
15. System.out.println(\"num = \" + num); 16. } catch(ArrayIndexOutOfBoundsException e){ 17. System.out.println(e.toString()); 18. System.exit(0);//退出jvm 19. } finally{//通常用于关闭(释放)资源 20.
System.out.println(\"finally\");//由于前面执行了System.exit(0);,故不会执行此语句。
21. }
22. System.out.println(\"over\"); 23. } 24. }
复制代码 运行结果:
因篇幅问题不能全部显示,请点此查看更多更全内容