在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);}