标签:处理 ArithmeticException System catch finally println 机制 异常 out
抛出异常
捕获异常
异常处理五个关键字:try、catch、finally、throw、throws
自定义异常:只需继承Exception
步骤:
1.创自定义异常类
2.方法中throw抛出或类上throws抛出或方法后throws抛出
3.try catch捕获并处理异常
package com.wuming.exception; public class Test { public static void main(String[] args) { int a=1; int b=0; try {//try监控区域 //System.out.println(a/b); new Test().a();//Exception in thread "main" java.lang.StackOverflowError,需用Throwable或error或exception捕获 }catch(ArithmeticException e){//catch捕获异常 System.out.println("程序出现异常,变量b不能为0"); }catch(Error e){ System.out.println("程序出现异常(用Error来看)");//一旦捕获异常(要看异常的分类走的),直接走finally }catch(Exception e){ System.out.println("程序出现异常(用Exception来看)"); }catch(Throwable e){//有多个捕获异常的关键字,顺序,只看Throwable必须放finally的前一个 System.out.println("程序出现异常(用Error来看)");//一旦捕获异常,直接走finally } finally {//处理善后工作 System.out.println("finally"); } //finally可以不要finally,但有finally一定会输出。假设有IO,资源要关闭 } public void a(){ b(); } public void b(){ a(); } }
package com.wuming.exception; public class Test1 { public static void main(String[] args) { try { new Test1().test(1,0); } catch (ArithmeticException e) {//在public void test(int a,int b)后面加 throws ArithmeticException,ctrl+alt+t后会出现ArithmeticException,不加throws ArithmeticException,ctrl+alt+t后会出现Exception e.printStackTrace(); } //throw用在方法中主动抛出异常//Exception in thread "main" java.lang.ArithmeticExceptionat com.wuming.exception.Test1.test(Test1.java:27)at com.wuming.exception.Test1.main(Test1.java:5) } /* public static void main(String[] args) { int a=1; int b=0; //try catch快捷键 ctrl+alt+t;先选中 try { if (b==0){ throw new ArithmeticException();//主动抛出异常用(throw和throws区别,后者用在方法上或类上,前者用在方法中,但这里没有用在方法中,不能抛出异常,看下面用在test()就抛出了) } System.out.println(a/b); } catch (Exception e) { // System.exit(1);//退出 System.out.println("Exception"); //e.printStackTrace();//打印错误的栈信息//java.lang.ArithmeticException: / by zeroat com.wuming.exception.Test1.main(Test1.java:9) } finally { System.out.println("finally"); } }*/ public void test(int a,int b) throws ArithmeticException{ if (b==0){// throw new ArithmeticException(); } System.out.println(a/b); } }
标签:处理,ArithmeticException,System,catch,finally,println,机制,异常,out 来源: https://blog.csdn.net/wanggang182007/article/details/122321041
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。