我是靠谱客的博主 鲜艳芝麻,这篇文章主要介绍Java语言之异常处理类,现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package step1; import java.util.Scanner; public class ThrowException { public static void function(String id) { //利用throws关键字声明该方法可能出现异常IllegalArgumentException /********** Begin *********/ if (id.length() == 7) { //输出ID合法时的语句 System.out.print("ID格式正确:"+id); } else { //利用throw关键字抛出异常IllegalArgumentException throw new IllegalArgumentException(); } /********** End *********/ } public static void main(String[] args) { Scanner sc=new Scanner(System.in); String id=sc.nextLine(); try { function(id); } catch (IllegalArgumentException e) { //可以看成一个flag? /********** Begin *********/ //输出ID不合法时的语句 System.out.print("ID长度应为7"); /********** End *********/ } } }

2

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package step2; import java.io.*; public class CatchException { public static void main(String[] args) { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String str; int letter=0,space=0,number=0,other=0; /********** Begin *********/ //补全try/catch块,异常类型为IOException try { str=reader.readLine();//必须放在try里面,因为要有一个返回值来判断是否抛出 char str1[]=str.toCharArray(); for (int i=0;i<str1.length;i ++) { if (Character.isLetter(str1[i])) { letter++; } else if (Character.isSpaceChar(str1[i])) { space++; } else if (Character.isDigit(str1[i])) { number++; } else other++; } System.out.println("letter="+letter +",space="+ space + ",number=" + number+",other="+other); }catch(IOException e){ e.printStackTrace(); } /********** End *********/ } }

3

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package step3; import java.util.Scanner; class MyException extends Exception { public MyException(String m) { super(m); } } public class MyExceptionTest { public static void main(String[] args) { try { Scanner scanner = new Scanner(System.in); int num = scanner.nextInt(); /********** Begin *********/ if(num<0) { throw new MyException("Number cannot be negative!"); } else System.out.print("The number you entered is: "+num); /********** End *********/ } catch(MyException e) { System.out.print(e); } } }

最后

以上就是鲜艳芝麻最近收集整理的关于Java语言之异常处理类的全部内容,更多相关Java语言之异常处理类内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(61)

评论列表共有 0 条评论

立即
投稿
返回
顶部