throws自定义抛出异常

论坛 期权论坛 脚本     
匿名技术用户   2020-12-28 19:37   546   0




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

 * **********************************************************************
 * *********************************************************************/





分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP