如何为语句抛出异常?

时间:2011-03-27 17:12:08

标签: java exception exception-handling

嗨! 我想为行

抛出异常
BarcodeNo=Long.parseLong(jTextField1.getText())

我这样做了

BarcodeNo=Long.parseLong(jTextField1.getText()) throw new NumberFormatException("Enter Numbers Only ");

但这种方式编译器抛出错误说明“;”需要

所以任何人都可以告诉我该怎么做?

由于

2 个答案:

答案 0 :(得分:2)

如果文本格式不正确,已经抛出异常。如果要更改异常消息,则必须捕获异常并抛出一个新异常:

try {
  BarcodeNo = Long.parseLong(jTextField1.getText());
} catch (NumberFormatException e) {
  throw new NumberFormatException("Enter Numbers Only");
}

我不建议您尝试将异常消息用作用户可见的消息 - 它们对于日志记录比显示最终用户更合理。

答案 1 :(得分:-1)

是的,你应该把

try
{
BarcodeNo=Long.parseLong(jTextField1.getText());
}
catch(Exception e)
{
throw new NumberFormatException("Enter Numbers Only ");

}