首页 / JAVA / JavaSE学习总结(八)
JavaSE学习总结(八)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了JavaSE学习总结(八),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2427字,纯文字阅读大概需要4分钟。
内容图文
![JavaSE学习总结(八)](/upload/InfoBanner/zyjiaocheng/1142/aa63c4590bb94721a61ff22999ca4ea5.jpg)
一、理解异常及异常处理的概念
异常就是在程序的运行过程中所发生的不正常的事件,它会中断正在运行的程序。
异常不是错误
程序中关键的位置有异常处理,提高程序的稳定性
二、掌握Java异常处理机制
Java的异常处理是通过5个关键字来实现的
try:尝试,把有可能发生错误的代码放在其中,必须有
catch:捕获,当发生异常时执行
finally:最终,不管是否有异常都将执行
throw:抛出,引发异常
throws:抛出多个,声明方法将产生某些异常
三、掌握try 、catch 、 finally 处理异常
3.1、try..catch
package com.zhangguo.chapter6.d1; import java.util.Scanner; public class Exception1 { public static void main(String[] args) { Scanner input=new Scanner(System.in); //int i=input.nextInt(); int i=Integer.parseInt(input.next()); System.out.println("您输入的是:"+i); System.out.println("程序结束了"); } }
异常处理:
package com.zhangguo.chapter6.d1; import java.util.Scanner; public class Exception1 { public static void main(String[] args) { try { Scanner input = new Scanner(System.in); int i = Integer.parseInt(input.next()); System.out.println("您输入的是:" + i); } catch (Exception exp) { System.out.println("发生异常了:" + exp.getMessage()); } System.out.println("程序结束了"); } }
结果:
3.2、try..catch..finally
finally在任何情况下都将执行,正常时会执行,不正常也会执行
package com.zhangguo.chapter6.d1; import java.util.Scanner; public class Exception1 { public static void main(String[] args) { try { Scanner input = new Scanner(System.in); int i = Integer.parseInt(input.next()); System.out.println("您输入的是:" + i); } catch (Exception exp) { System.out.println("发生异常了:" + exp.getMessage()); }finally { System.out.println("输入结束"); } System.out.println("程序结束了"); } }
结果:
1
您输入的是:1
输入结束
程序结束了
如果用户输入是的xyz
四、掌握throw 抛出异常、throws 声明异常
4.1、java中常用的异常
![技术分享](/img/jia.gif)
4.2、throw..throws
package com.zhangguo.chapter6.d1; public class Exception2 { public static void main(String[] args) { try { System.out.println(div(30,3)); } catch (Exception e) { //输出异常的堆栈信息 e.printStackTrace(); } try { System.out.println(div(3,0)); } catch (Exception e) { System.out.println(e.getMessage()); } } //throws 声明方法将可能抛出异常 public static int div(int n1,int n2) throws Exception{ if(n2==0){ //抛出异常 throw new Exception("除数不能为零"); } return n1/n2; } }
运行结果:
五、掌握自定义异常
public class ArithmeticException extends RuntimeException { private static final long serialVersionUID = 2256477558314496007L; /** * Constructs an {@code ArithmeticException} with no detail * message. */ public ArithmeticException() { super(); } /** * Constructs an {@code ArithmeticException} with the specified * detail message. * * @param s the detail message. */ public ArithmeticException(String s) { super(s); } }
原文:http://www.cnblogs.com/zhanglixina/p/7694757.html
内容总结
以上是互联网集市为您收集整理的JavaSE学习总结(八)全部内容,希望文章能够帮你解决JavaSE学习总结(八)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。