
求大神指点关于java异常的一道编程题,在下感激不尽!
编写一个异常类ExampleException,再编写一个类Test,该类有一个产生异常的方法。publicvoidshow(Stringm)throwsExampleE...
编写一个异常类Example Exception,再编写一个类Test,该类有一个产生异常的方法。
public void show (String m)throws ExampleException,要求参数 m等于“ABC”时,方法抛出一个ExampleException对象。最后编写主类,在main方法中使用Test 创建一个对象,让该对象调用show方法 展开
public void show (String m)throws ExampleException,要求参数 m等于“ABC”时,方法抛出一个ExampleException对象。最后编写主类,在main方法中使用Test 创建一个对象,让该对象调用show方法 展开
展开全部
public class Test {
public void show(String m) throws ExampleException {
if ("ABC".equals(m)) {
throw new ExampleException("您传入的参数错误!", m);// 抛出异常
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test test = new Test();
try {
test.show("ABC");
} catch (ExampleException e) {
// TODO Auto-generated catch block
System.err.println("Error:" + e.getMessage() + "传入的参数为"
+ e.getStr());// 打印异常信息.
}
}
}
class ExampleException extends Exception // 创建自定义异常,继承自Exception
{
private String str;// 获取方法参数
public ExampleException() {
super();
// TODO Auto-generated constructor stub
}
public ExampleException(String message, String str) {
super(message);// 调用父类构造器来显示异常信息
this.str = str;
}
public String getStr() {
return str;
}
}
控制台信息信息:
Error:您传入的参数错误!传入的参数为ABC
public void show(String m) throws ExampleException {
if ("ABC".equals(m)) {
throw new ExampleException("您传入的参数错误!", m);// 抛出异常
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test test = new Test();
try {
test.show("ABC");
} catch (ExampleException e) {
// TODO Auto-generated catch block
System.err.println("Error:" + e.getMessage() + "传入的参数为"
+ e.getStr());// 打印异常信息.
}
}
}
class ExampleException extends Exception // 创建自定义异常,继承自Exception
{
private String str;// 获取方法参数
public ExampleException() {
super();
// TODO Auto-generated constructor stub
}
public ExampleException(String message, String str) {
super(message);// 调用父类构造器来显示异常信息
this.str = str;
}
public String getStr() {
return str;
}
}
控制台信息信息:
Error:您传入的参数错误!传入的参数为ABC
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询