package 异常处理;
class inrangeexception extends Exception{
inrangeexception(int wrongnum){
super(wrongnum + "is not a validate num");
System.out.println("exception was throwed ");
}
}
class validation {
public void inrange(int num) throws Exception{
if(num > 0 && num < 1000){
System.out.println(num + " in the range");
}
else{
throw new inrangeexception(num);
}
}
}
package 异常处理;
import java.util.Scanner;
public class test_inrange {
public static void main(String[] args) {
validation v = new validation();
int num = 0;
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
try {
v.inrange(num);
} catch (Exception e) {
System.out.println(e.getMessage());
//如果此处添加 return ,永远别想输出 num 到屏幕上
//reason:catch块中添加 return ,则 catch 之后的语句将无法显示
}
System.out.println("the later scentence in the programe " + num);
}
}
/***********************************************************************
* *********************************************************************
//异常抛出:
45444
exception was throwed
45444is not a validate num
the later scentence in the programe 45444
* **********************************************************************
* **********************************************************************
//无异常情况:
4
4 in the range
the later scentence in the programe 4
* **********************************************************************
* *********************************************************************/