处理异常机制
异常的多态特性
public class SystemExitAndFinally { public static void main(String[] args) { try { System.out.println( "in main" ); throw new Exception( "Exception is thrown in main" ); //System.exit(0); } catch (Exception e) { System.out.println(e.getMessage()); System.exit( 0 ); } finally { System.out.println( "in finally" ); } } } |
运行结果:
finally不会每次都执行,例如以上程序,当执行完throw new Exception("Exception is thrown in main");语句后便关闭了程序,System.exit(0)可以终止程序。
编写一个程序,此程序在运行时要求用户输入一个 整数,代表某门课的考试成绩,程序接着给出“不及格”、“及格”、“中”、“良”、“优”的结论。
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
|
package Test; import java.util.InputMismatchException; import java.util.Scanner; public class dengji { public static void main(String[] args) { Scanner scanner= new Scanner(System.in); int n=- 1 ; try { System.out.print( "请输入一个范围为0~100的整数:" ); n=scanner.nextInt(); if ( 0 <=n&&n< 60 ){ System.out.println( "不及格" ); } if ( 60 <=n&&n< 80 ) { System.out.println( "中" ); } if ( 80 <=n&&n< 90 ) { System.out.println( "良" ); } if ( 90 <=n&&n<= 100 ) { System.out.println( "优" ); } if (n< 0 ||n> 100 ) { System.out.println( "输入超出范围!" ); } } catch (InputMismatchException e) { System.out.println( "输入不是整数" ); } } } |