站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2SE 专题java异常问题不知道错在哪了?

java异常问题不知道错在哪了?

摘要: java异常问题不知道错在哪了?


小弟编了个程序
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/**
* @author Administrator
*
* TODO 要更改此生成的类型注释的模板,请转至
* 窗口 - 首选项 - Java - 代码样式 - 代码模板
*/
public class ExceptionApplet extends Applet implements ActionListener
{
Label L1,L2;
TextField tf1,tf2;
String answerStr;
double d1,d2;
public void init()
{
L1=new Label(-#34;请输入0到100之间的数-#34;);
add(L1);
tf1=new TextField(6);
add(tf1);
L2=new Label(-#34;两数相除的结果-#34;);
add(L2);
tf2=new TextField(6);
add(tf2);
tf1.addActionListener(this);
tf2.addActionListener(this);
}
public void actionPerformed(ActionEvent evt)
{
try
{
d1=Double.valueOf(tf1.getText()).doubleValue();
d2=Double.valueOf(tf2.getText()).doubleValue();
String result=-#34;两数相除的结果:-#34;+Result();
L2.setText(result);
}
catch(NumberFormatException e)
{
answerStr=-#34;输入的必须是数字-#34;;
L2.setText(answerStr);
}
repaint();
}
public double Result() throws NumberRangeException
{
double answer=0;
try
{
if((d1-#60;0) || (d1-#62;100) || (d2-#60;0) || (d2-#62;100) )
{
NumberRangeException ee=new NumberRangeException(-#34;输入的数字不在指定的范围-#34;);
throw ee;
}
answer=d1/d2;
}
catch(ArithmeticException eee)
{
answerStr=eee.toString();
}
return answer;
}
}
class NumberRangeException extends Exception
{
NumberRangeException(String msg)
{
super(msg);
}
}


编译后出现

ExceptionApplet.java:35: unreported exception NumberRangeException; must be caught or declared to be thrown
String result=-#34;两数相除的结果:-#34;+Result();
不知道是什么原因请教各位!


Result() 可能会抛出 NumberRangeException
你没有try catch 处理,或者继续抛出。


你没有捕获Result()方法要抛出的异常NumberRangeException,而是捕获了一个NumberFormatException。


你的Result()方法声明了抛出NumberRangeException异常

但你的main方法中调用Result并没有catch或抛出该异常

catch(NumberFormatException e)
{
answerStr=-#34;输入的必须是数字-#34;;
L2.setText(answerStr);
}
再catch一下NumberRangeException


你改成这个样子看哈行不,应该就是这个样子!!
{
if((d1-#60;0) || (d1-#62;100) || (d2-#60;0) || (d2-#62;100) )
{
NumberRangeException ee=new NumberRangeException(-#34;输入的数字不在指定的范围-#34;);
throw ee;
}
answer=d1/d2;
}
catch(ArithmeticException eee)
{
answerStr=eee.toString();
}
catch (NumberRangeException e)
{
answerStr= e.toString();
}
return answer;
}
}



非常感谢各位问题迎刃而解


↑返回目录
前一篇: java里怎样将获得系统日期和时间?
后一篇: 关于StreamTokenizer中的TT_NUMBER