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 }

posted on 2019-12-22 11:43  Chenjin123  阅读(275)  评论(0编辑  收藏  举报