创建一个类继承于Exception类;添加构造方法;在一个方法中使用throw抛出该异常,
1个回答
2016-10-11
展开全部
public class MyClass {
private static final int STRING_LENGTH = 10;
public static void main(String[] args) {
String s;
try {
s = getString();
} catch (StringLengthTooLargeException e) {
e.printStackTrace();
s = "error";
}
System.out.println(s);
}
private static String getString() throws StringLengthTooLargeException {
String s = new Scanner(System.in).next();
if (s.length() > STRING_LENGTH) {
throw new StringLengthTooLargeException();
}
return s;
}
}
class StringLengthTooLargeException extends Exception {
public StringLengthTooLargeException() {
super("字符串长度超过设定长度");
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询