JAVA 异常处理部分问题!!求教!!!!

定义一个StringTooLongException异常,表示一个String对象的长度太长。在main()中,让用户输入字符串,一直到程序被终止。如果读入的字符串超过20个字符,就抛出这个异常。
程序写出来了 但是不知道错在哪里了??好纠结!!!一天了都编不出来!求助!!跪谢!!求详细指点或求代码!!
package 异常;
class StringTooLongException extends Exception{
StringTooLongException(){
super();
}
StringTooLongException(String s){
super(s);
}
}
class LongString{
int i;
public void setLong(int i) throws StringTooLongException{
if(i>=20){
throw new StringTooLongException("error!");
}
else
System.out.println("right");
}
}

package 异常;

import java.io.IOException;

public class testString {

public static void main(String[] args) {
char ch;
int i=0;
try{
for(;;){

ch=(char) System.in.read();
System.out.println(ch);
i++;
setLong(i);
}
catch (IOException | StringTooLongException e ){
System.out.println(e+"throwed");

}
}

你的try把catch都包进去了,而且异常只是一个名字抛出异常应该由异常产生地方抛,所以
public void setLong(int i) throws StringTooLongException{
if(i>=20){
throw new StringTooLongException("error!");
}
else 
System.out.println("right");
}
应该在testString类里面,且i应该为类属性而不是局部变量。

追问

那怎么改呀

温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网