自定义异常类MyException,该类继承自Exception类,类中只有含一个字符串参数msg的构造方法,构造方法中只
自定义异常类MyException,该类继承自Exception类,类中只有含一个字符串参数msg的构造方法,构造方法中只有一条语句super(msg)——调用父类的构造...
自定义异常类MyException,该类继承自Exception类,类中只有含一个字符串参数msg的构造方法,构造方法中只有一条语句super(msg)——调用父类的构造方法。另外,编写自定义类MyAdd,类中只有一个私有的整型变量x;有两个公有方法void add(int x)和int getX(),其中add(int x)的功能是把参数x的值加到类中的变量x中(但要求x的值在0~100之间,否则抛出自定义异常MyException类的对象),getX()方法返回x的值。编写应用程序TestMyException.java,在其main方法中创建MyAdd类对象,并调用MyAdd类的set方法共3次,分别设置x的值为88、66、128,每次都输出类中变量x的值,编译、运行程序TestMyException.java,观察程序的输出结果。
展开
展开全部
public class TestMyException{
public static void main(String args[]) throws MyException{
MyAdd add = new MyAdd();
add.add(88);
System.out.println("add 88, result is: " + add.getX());
add.add(66);
System.out.println("add 66, result is: " + add.getX());
add.add(128);
System.out.println("add 128, result is: " + add.getX());
}
}
class MyException extends Exception {
public MyException(String msg) {
super(msg);
}
}
class MyAdd {
private int x;
public void add(int x) throws MyException{
if(x >= 0 && x <= 100){
this.x += x;
}else{
throw new MyException("x should be between 0 and 100!");
}
}
public int getX(){
return x;
}
public void setX(int x){
this.x = x;
}
}
-----------------------
add 88, result is: 88
add 66, result is: 154
Exception in thread "main" MyException: x should be between 0 and 100!
at MyAdd.add(TestMyException.java:29)
at TestMyException.main(TestMyException.java:10)
public static void main(String args[]) throws MyException{
MyAdd add = new MyAdd();
add.add(88);
System.out.println("add 88, result is: " + add.getX());
add.add(66);
System.out.println("add 66, result is: " + add.getX());
add.add(128);
System.out.println("add 128, result is: " + add.getX());
}
}
class MyException extends Exception {
public MyException(String msg) {
super(msg);
}
}
class MyAdd {
private int x;
public void add(int x) throws MyException{
if(x >= 0 && x <= 100){
this.x += x;
}else{
throw new MyException("x should be between 0 and 100!");
}
}
public int getX(){
return x;
}
public void setX(int x){
this.x = x;
}
}
-----------------------
add 88, result is: 88
add 66, result is: 154
Exception in thread "main" MyException: x should be between 0 and 100!
at MyAdd.add(TestMyException.java:29)
at TestMyException.main(TestMyException.java:10)
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询