在java自定义异常中,如何使异常字符串进入设定的异常解决方案中 - 爱问答

(爱问答)

在java自定义异常中,如何使异常字符串进入设定的异常解决方案中

class NoLowerLetter extends Exception{

 

String message;

   NoLowerLetter(String c){

    message=c+"不对啊,老铁! ";

}

public String getMesssage(){

  return message;

}

}

class NoDigit extends Exception{

   String message;

   NoDigit(String d){

    message=d+"老铁,不对! ";

}

public String getMesssage(){

  return message;

}

 

}

class People{

public void printLetter(String c) throws NoLowerLetter{

int len = c.length();

   if(len>=7){

       NoLowerLetter ex=new NoLowerLetter(c);  

       throw(ex);}

   else

   {

   String e=c+"    good";

  System.out.printf("牛啊,你得到的字符串是:%s ",e);}

}

public void printDigit(String d) throws NoDigit{

int len=d.length();

if(len<=8){

   NoDigit ex=new NoDigit(d);

   throw(ex);}

else

{

String f=d+"    wonderful";

System.out.printf("秀啊,你得到的字符串是:%s ",f);}

}

}

public class Example5_19{

 public static void main(String args[]) {

  People people=new People();

  try{

  String c="hisue";

  people.printLetter(c);

  String d="hgjasdhkd";

  people.printLetter(d);

      }

 catch(NoLowerLetter e){           System.out.println(e.getMessage());} 

try {

  String d="akjhf";

  people.printDigit(d);}

  catch (NoDigit f) {

// TODO Auto-generated catch block

  System.out.println(f.getMessage());

}

 

}

}


编写自定义异常类实际上是继承一个API标准异常类,用新定义的异常处理信息覆盖原有信息的过程。常用的编写自定义异常类的模式如下:public class CustomException extends Exception { //或者继承任何标准异常类public CustomException() {} //用来创建无参数对象public CustomException(String message) { //用来创建指定参数对象super(message); //调用超类构造器}}当然也可选用Throwable作为超类。其中无参数构造器为创建缺省参数对象提供了方便。第二个构造器将在创建这个异常对象时提供描述这个异常信息的字符串,通过调用超类构造器向上传递给超类,对超类中的toString()方法中返回的原有信息进行覆盖。来讨论一个具体例子。假设程序中需要验证用户输入的表示年龄的数据必须是正整数值。我们可以按照以上模式编写这个自定义异常类如下:public class NegativeAgeException extends Exception {//或者:extends Throwablepublic NegativeAgeException() {}public NegativeAgeException(String message) {super(message);}}下面是应用这个自定义异常类的例子:try{String ageString = JOptionPane.showInputDialog("Enter your age: ");if (Integer.parseInt(ageString) < 0)throw new NegativeAgeException("Please enter a positive age");elseJOptionPane.showMessageDialog(null, ageString, "Age", 1);}catch(NegativeAgeException e){System.out.println(e);}

相关标签:java

下一篇:分析程序中100毫秒延时的误差;若对延时时间的精度要求高的话,应该怎么办?

上一篇:基于客户表,按照所在城市统计每个城市客户数目,结果按照数目降序排序用SQl怎样表述?

热门标签:
excel 网盘 破解 word dll
最新更新:
微软重新评估新的Outlook的使用时机 联想推出搭载联发科Helio G80芯片组的Tab M9平板 英特尔创新大赛时间确定! 微软Edge浏览器在稳定渠道中推出Workspaces功能 英伟达RTX4060TiGPU推出MaxSun动漫主题! 谷歌地图为用户提供了街景服务! GameSir 在T4 Kaleid中推出了一款出色的控制器! 微软开始在Windows 11 中测试其画图应用程序的新深色模式! LG电子推出全球首款无线OLED电视 英伟达人工智能芯片崭露头角! Steam Deck可以玩什么游戏-Steam Deck价格限时优惠 雷蛇推出CobraPro鼠标 Kindle电子阅读器可以访问谷歌商店吗 Windows10如何加入组策略 window10图片查看器怎么没有了?