①class ScoreException extends Exception {
int m;
ScoreException(int m) {
this.m=m;
}
int getMess() {
return m;
}
}
class Teacher {
public int giveScore(int score) throws
ScoreException {
if(score>100 || score<0)
throw new ScoreException(score);
return score;
}
}
public class E {
public static void main(String args[]) {
Teacher t = new Teacher();
int m=0,n=0;
try { m=t.giveScore(199);
m=t.giveScore(69);
}
catch (ScoreException e) {
n=e.getMess();
}
System.out.printf("%d:%d",m,n);
}
}
②class ScoreException extends Exception {
int m;
ScoreException(int m) {
this.m=m;
}
int getMess() {
return m;
}
}
class Teacher {
public int giveScore(int score) throws
ScoreException {
if(score>100 || score<0)
throw new ScoreException(score);
return score;
}
}
public class E {
public static void main(String args[]) {
Teacher t = new Teacher();
int m=0,n=0;
try { m=t.giveScore(100);
m=t.giveScore(101);
}
catch (ScoreException e) {
n=e.getMess();
}
System.out.printf("%d:%d",m,n);
}
}
①②两题的结果有何区别,请说明一下,给出解题思路?
t1:m=t.giveScore(199);时抛异常走到catch段代码,m=t.giveScore(69);不执行,所以m=0,catch里面的ScoreException 对象的m值是199,所以n=199.
输出0,199
t2:m=t.giveScore(100);执行了,此时m=100。m=t.giveScore(101)抛异常,执行catch段n的赋值n=e.getMess();
输出100,101
谢谢。有点明白了