首页 / JAVA / 32.Java基础_异常
32.Java基础_异常
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了32.Java基础_异常,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2969字,纯文字阅读大概需要5分钟。
内容图文
JVM虚拟机默认异常处理机制
Java异常处理:
1.try...catch...
2.throw
1.try...catch...
1 public class test{ 2 public static void main(String[] args) { 3 System.out.println("开始"); 4 method(); 5 System.out.println("结束"); 6 } 7 public static void method(){ 8 int[] arr={1,2,3}; 9 try { 10 System.out.println(arr[3]); //访问超出索引 11 } 12 catch (ArrayIndexOutOfBoundsException e){ 13 e.printStackTrace(); 14 } 15 } 16 } 17 /* 18 开始 19 java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 20 at pack2.test.method(test.java:13) 21 at pack2.test.main(test.java:7) 22 结束 23 */
Exception异常类常用方法
编译时异常和运行时异常
2.throws
throws将异常抛出去,让try_catch_来处理
1 import java.text.ParseException; 2 import java.text.SimpleDateFormat; 3 import java.util.Date; 4 public class test{ 5 public static void main(String[] args) { 6 System.out.println("开始"); 7 try { 8 method(); 9 } 10 catch (ArrayIndexOutOfBoundsException e){ 11 e.printStackTrace(); 12 } 13 try { 14 method2(); 15 } 16 catch (ParseException e){ 17 e.printStackTrace(); 18 } 19 System.out.println("结束"); 20 } 21 //编译时异常,不加throws ParseException不能编译 22 public static void method2() throws ParseException { 23 String s="2048-08-09"; 24 SimpleDateFormat sdf=new SimpleDateFormat("yyy-MM-dd"); 25 Date d=sdf.parse(s); 26 System.out.println(d); 27 } 28 //运行时异常,不加throws ArrayIndexOutOfBoundsException可以编译 29 public static void method() throws ArrayIndexOutOfBoundsException{ 30 int[] arr={1,2,3}; 31 System.out.println(arr[3]); 32 } 33 } 34 /* 35 开始 36 java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 37 at pack2.test.method(test.java:36) 38 at pack2.test.main(test.java:13) 39 Sun Aug 09 00:00:00 CST 2048 40 结束 41 */
自定义异常
1 public class ScoreException extends Exception{ 2 public ScoreException() {} 3 public ScoreException(String message) { 4 super(message); 5 } 6 } 7 8 public class Teacher{ 9 public void checkScore(int score) throws ScoreException{ 10 if(score<0||score>100){ 11 throw new ScoreException(); //抛出异常对象 12 } 13 else { 14 System.out.println("分数正常"); 15 } 16 } 17 } 18 19 import java.util.Scanner; 20 public class test{ 21 public static void main(String[] args) { 22 Scanner sc=new Scanner(System.in); 23 System.out.println("请输入分数:"); 24 int score=sc.nextInt(); 25 Teacher t=new Teacher(); 26 try { 27 t.checkScore(score); 28 } 29 catch (ScoreException e){ 30 e.printStackTrace(); 31 } 32 } 33 }
内容总结
以上是互联网集市为您收集整理的32.Java基础_异常全部内容,希望文章能够帮你解决32.Java基础_异常所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。