Java复习(4)-异常处理
2016-03-13 15:03
573 查看
1.try-catch-finally
运行结果:
2.throw 和throws
public class ThrowableTry { public static void main(String[] args) { // TODO Auto-generated method stub int a,b; int[] c = new int[3]; try{ a = 0; c[3] = 3; b = 5/a;//先碰到上面的异常,这个异常就不运行了。 System.out.println("需要检验的程序"); } catch(ArithmeticException e){ System.out.println("发生ArithmeticException "+e); } catch(Exception e){ System.out.println("发生ArrayIndexOutOfBoundsExceptionn "+e); } finally{ System.out.println("over");//finally是一定会运行的 } } }
运行结果:
发生ArrayIndexOutOfBoundsExceptionn java.lang.ArrayIndexOutOfBoundsException: 3 over
2.throw 和throws
public class Throws { public static void main(String[] args){ //throwsTest(); throwTest(); } //测试中发现不写throws以及后面内容也是可以的,怎么回事? public void methodName(int x) throws ArrayIndexOutOfBoundsException,ArithmeticException{ System.out.println(x); if(x == 0){ System.out.println("没有异常"); return; } else if(x == 1){ int[] a = new int[3]; a[3] = 5; } else if(x == 2){ int i = 0; int j = 5/i; } } public static void throwsTest(){ Throws a = new Throws(); try { a.methodName(0); } catch(Exception e){ System.out.println("异常:"+e); } try{ a.methodName(1); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("异常:"+e); } try{ a.methodName(2); } catch(ArithmeticException e){ System.out.println("异常:"+e); } } public void methodName(){ try{ throw new ArrayIndexOutOfBoundsException();//这里的throw 必须加 } catch(ArrayIndexOutOfBoundsException aoe){ throw aoe; } } public static void throwTest(){ Throws a = new Throws(); try{ a.methodName(); } catch(ArrayIndexOutOfBoundsException aoe){ System.out.println("异常:"+aoe); } } }
相关文章推荐
- java程序设计基础_陈国君版第五版_第十章例题
- Java复习(3)-内部类
- java程序设计基础_陈国君版第五版_第九章例题
- SpringMVC+Mybatis框架整合java源码 maven mysql
- java程序设计基础_陈国君版第五版_第八章例题
- 安装配置Eclipse过程
- Java嵌套类
- java程序设计基础_陈国君版第五版_第七章例题
- springMVC-1
- 唯爱小粽子:SpringMVC中DispatcherServlet详解
- Eclipse Plugin Installation and Windows User Access Control
- struts2 helloworld 的404错误
- java线程传统VS现代【3】
- java线程传统VS现代【2】
- java队列和栈的使用
- Java内部类的自我理解
- Java并发包中CyclicBarrier的工作原理、使用示例
- 20145221 《Java程序设计》第二周学习总结
- Eclipse/MyEclipse配置SVN插件
- 如何解决eclipse中没有plugin development